
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find the maximum repeating number in O(n) time and O(1) extra space in Python
Suppose we have an array of size n, if the elements in the array, are in range from 0 to k-1. Where k is denoted as a positive integer and k <= n. We have to find the maximum repeating number in this array.
So, if the input is like k = 8 and A = [3, 4, 4, 6, 4, 5, 2, 8], then the output will be 4.
To solve this, we will follow these steps −
n := size of A
for i in range 0 to n, do
A[A[i] mod k] := A[A[i] mod k] + k
max_val := A[0]
result := 0
for i in range 1 to n, do
if A[i] > max_val, then
max_val := A[i]
result := i
return result
Example
Let us see the following implementation to get better understanding −
def get_max_repeating(A, k): n = len(A) for i in range(n): A[A[i]%k] += k max_val = A[0] result = 0 for i in range(1, n): if A[i] > max_val: max_val = A[i] result = i return result A = [3, 4, 4, 6, 4, 5, 2, 8] k = 8 print(get_max_repeating(A, k))
Input
[3, 4, 4, 6, 4, 5, 2, 8], 8
Output
4
- Related Questions & Answers
- Find duplicates in O(n) time and O(1) extra space - Set 1 in C++
- Find maximum in a stack in O(1) time and O(1) extra space in C++
- Rearrange positive and negative numbers in O(n) time and O(1) extra space in C++
- Find median of BST in O(n) time and O(1) space in Python
- Find median of BST in O(n) time and O(1) space in C++
- Count frequencies of all elements in array in O(1) extra space and O(n) time in C++
- Find duplicate in an array in O(n) and by using O(1) extra space in C++
- Print left rotation of array in O(n) time and O(1) space in C Program.
- Count Fibonacci numbers in given range in O(Log n) time and O(1) space in C++
- Check for balanced parentheses in an expression O(1) space O(N^2) time complexity in Python
- Print n x n spiral matrix using O(1) extra space in C Program.
- Check for balanced parentheses in an expression - O(1) space - O(N^2) time complexity in C++
- Check if array elements are consecutive in O(n) time and O(1) space (Handles Both Positive and negative numbers) in Python
- Check if the characters in a string form a Palindrome in O(1) extra space in Python
- Find duplicates in constant array with elements 0 to N-1 in O(1) space in C++
Advertisements