
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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 Articles
- Find maximum in a stack in O(1) time and O(1) extra space in C++
- Find duplicates in O(n) time and O(1) extra space - Set 1 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
- 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++
- Find median of BST in O(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.
- 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++
- Reverse Individual Words With O(1) Extra Space
- Check if array elements are consecutive in O(n) time and O(1) space (Handles Both Positive and negative numbers) in Python
- Check for balanced parentheses in an expression - O(1) space - O(N^2) time complexity in C++
- Check if the characters in a string form a Palindrome in O(1) extra space in Python

Advertisements