GeeksforGeeks App
Open App
Browser
Continue

# Find X such that most Array elements are of form (X + p*K)

Given an array arr[] and a number K, the task is to find a value X such that maximum number of array elements can be expressed in the form (X + p*K).

Note: If there are multiple possible values of X, print the minimum among them.

Examples:

Input: arr[] = {1, 3, 5, 2, 4, 6}, k = 2
Output: 1
Explanation: On choosing 1 the elements of the form 1 + 2* p are 1, 3, 5 so 3 which is the maximum count of elements of the given form and 1 is the minimum number satisfying the condition, thus the output will be 1.

Input : arr[] = {4, 10, 50}, k = 100
Output: 4
Explanation: On choosing any number we get only that number possible of that form at p = 0 so answer is minimum of the array thus 4 will be the output.

Approach: This can be solved using the following idea.

Since a number X from is to be chosen such that the most elements in the array should be of the form y = X + p * K, where K is a constant, so we can see that X is the remainder when y is divided by K.

So the number that is going to be chosen should be the remainder that is occurring maximum times when array elements are divided by K.

Follow the steps mentioned below to solve the problem:

• Initialize a hashmap m to store the frequencies of the remainders.
• Initialize res = INT_MAX to store the number to be chosen.
• Initialize max_rem to store the maximum frequency of remainders when divided by K.
• Traverse through the array and compute the remainder when divided by the K and store the frequency in the hashmap m.
• Store the maximum frequency of remainders in the max_rem variable.
• Now Traverse through the array and choose the minimum number of many elements that have the same frequency of remainders.
• Return the res.

Below is the implementation of the above approach.

## C++

 `// C++ code to implement the approach` `#include ``using` `namespace` `std;` `// Function to choose the number which has``// maximum numbers of the array of the``// form n+k*x``int` `ChooseNumber(``int` `arr[], ``int` `k, ``int` `n)``{``    ``// Initializing a hashmap to store the``    ``// frequencies of the remainders``    ``unordered_map<``int``, ``int``> m;` `    ``// Initialize res = INT_MAX to store``    ``// the number to be chosen``    ``int` `res = INT_MAX;` `    ``// Initialize max_rem to store the``    ``// maximum frequency of remainders``    ``// when divided by k``    ``int` `max_rem = INT_MIN;``    ``for` `(``int` `i = 0; i < n; i++) {``        ``int` `rem = arr[i] % k;``        ``m[rem]++;``        ``if` `(max_rem < m[rem])``            ``max_rem = m[rem];``    ``}` `    ``// Traverse through the array and``    ``// choose the minimum number if many``    ``// elements have the same frequency``    ``// of remainders``    ``for` `(``int` `i = 0; i < n; i++) {``        ``if` `(max_rem == m[arr[i] % k]) {``            ``res = min(res, arr[i]);``        ``}``    ``}` `    ``// Return the result``    ``return` `res;``}` `// Driver function``int` `main()``{``    ``int` `arr[] = { 1, 3, 5, 2, 4, 6 };``    ``int` `K = 2;``    ``int` `N = ``sizeof``(arr) / ``sizeof``(arr[0]);` `    ``// Function call``    ``cout << ChooseNumber(arr, K, N);` `    ``return` `0;``}`

## Java

 `import` `java.io.*;``import` `java.util.*;``public` `class` `Main {``  ``static` `int` `ChooseNumber(``int``[] arr, ``int` `k, ``int` `n)``  ``{``    ` `    ``// Initializing a hashmap to store the``    ``// frequencies of the remainders``    ``HashMap m = ``new` `HashMap<>();` `    ``// Initialize res = INT_MAX to store``    ``// the number to be chosen``    ``int` `res = Integer.MAX_VALUE;` `    ``// Initialize max_rem to store the``    ``// maximum frequency of remainders``    ``// when divided by k``    ``int` `max_rem = Integer.MIN_VALUE;``    ``for` `(``int` `i = ``0``; i < n; i++) {``      ``int` `rem = arr[i] % k;``      ``m.put(rem, m.getOrDefault(rem, ``0``) + ``1``);``      ``if` `(max_rem < m.getOrDefault(rem, ``0``))``        ``max_rem = m.getOrDefault(rem, ``0``);``    ``}` `    ``// Traverse through the array and``    ``// choose the minimum number if many``    ``// elements have the same frequency``    ``// of remainders``    ``for` `(``int` `i = ``0``; i < n; i++) {``      ``if` `(max_rem == m.getOrDefault(arr[i] % k, ``0``)) {``        ``res = Math.min(res, arr[i]);``      ``}``    ``}` `    ``// Return the result``    ``return` `res;``  ``}` `  ``public` `static` `void` `main(String[] args)``  ``{``    ``int``[] arr = { ``1``, ``3``, ``5``, ``2``, ``4``, ``6` `};``    ``int` `K = ``2``;``    ``int` `N = ``6``;` `    ``// Function call``    ``System.out.println(ChooseNumber(arr, K, N));``  ``}``}` `// This code is contributed by garg28harsh.`

## Python3

 `# Python code to implement the approach` `# Function to choose the number which has``# maximum numbers of the array of the``# form n+k*x``def` `ChooseNumber(arr,  k,  n):``  ` `    ``# Initializing a hashmap to store the``    ``# frequencies of the remainders``    ``m ``=` `{}``    ``for` `i ``in` `range``(n``+``1``):``        ``m[i] ``=` `0` `    ``# Initialize res = 1e9 to store``    ``# the number to be chosen``    ``res ``=` `1e9` `    ``# Initialize max_rem to store the``    ``# maximum frequency of remainders``    ``# when divided by k``    ``max_rem ``=` `-``1e9``    ``for` `i ``in` `range``(n):``        ``rem ``=` `arr[i] ``%` `k``        ``m[rem] ``+``=` `1``        ``if` `(max_rem < m[rem]):``            ``max_rem ``=` `m[rem]` `    ``# Traverse through the array and``    ``# choose the minimum number if many``    ``# elements have the same frequency``    ``# of remainders``    ``for` `i ``in` `range``(n):``        ``if` `(max_rem ``=``=` `m[arr[i] ``%` `k]):``            ``res ``=` `min``(res, arr[i])` `    ``# Return the result``    ``return` `res` `# Driver function``arr ``=` `[``1``, ``3``, ``5``, ``2``, ``4``, ``6``]``K ``=` `2``N ``=` `len``(arr)` `# Function call``print``(ChooseNumber(arr, K, N))` `# this code is contributed by vikkycirus`

## C#

 `// C# code for the above approach``using` `System;``using` `System.Collections.Generic;` `class` `GFG {``  ``static` `int` `ChooseNumber(``int``[] arr, ``int` `k, ``int` `n)``  ``{` `    ``// Initializing a hashmap to store the``    ``// frequencies of the remainders``    ``Dictionary<``int``, ``int``> m = ``new` `Dictionary<``int``, ``int``>();` `    ``// Initialize res = INT_MAX to store``    ``// the number to be chosen``    ``int` `res = Int32.MaxValue;` `    ``// Initialize max_rem to store the``    ``// maximum frequency of remainders``    ``// when divided by k``    ``int` `max_rem = Int32.MinValue;``    ``for` `(``int` `i = 0; i < n; i++) {``      ``int` `rem = arr[i] % k;``      ``m[rem] = m.GetValueOrDefault(rem, 0) + 1;``      ``if` `(max_rem < m.GetValueOrDefault(rem, 0))``        ``max_rem = m.GetValueOrDefault(rem, 0);``    ``}` `    ``// Traverse through the array and``    ``// choose the minimum number if many``    ``// elements have the same frequency``    ``// of remainders``    ``for` `(``int` `i = 0; i < n; i++) {``      ``if` `(max_rem``          ``== m.GetValueOrDefault(arr[i] % k, 0)) {``        ``res = Math.Min(res, arr[i]);``      ``}``    ``}` `    ``// Return the result``    ``return` `res;``  ``}` `  ``public` `static` `void` `Main()``  ``{``    ``int``[] arr = { 1, 3, 5, 2, 4, 6 };``    ``int` `K = 2;``    ``int` `N = 6;` `    ``// Function call``    ``Console.WriteLine(ChooseNumber(arr, K, N));``  ``}``}` `// This code is contributed by Samim Hossain Mondal.`

## Javascript

 `// JS code to implement the approach` `// Function to choose the number which has``// maximum numbers of the array of the``// form n+k*x``function` `ChooseNumber(arr,  k,  n)``{``    ``// Initializing a hashmap to store the``    ``// frequencies of the remainders``    ``let m = {};``    ``for``(let i = 0; i < n + 1; i++)``    ``{``        ``m[i] = 0;``    ``}` `    ``// Initialize res = let_MAX to store``    ``// the number to be chosen``    ``let res = Number.MAX_VALUE;` `    ``// Initialize max_rem to store the``    ``// maximum frequency of remainders``    ``// when divided by k``    ``let max_rem = Number.MIN_VALUE;``    ``for` `(let i = 0; i < n; i++) {``        ``let rem = arr[i] % k;``        ``m[rem]++;``        ``if` `(max_rem < m[rem])``            ``max_rem = m[rem];``    ``}` `    ``// Traverse through the array and``    ``// choose the minimum number if many``    ``// elements have the same frequency``    ``// of remainders``    ``for` `(let i = 0; i < n; i++) {``        ``if` `(max_rem == m[arr[i] % k]) {``            ``res = Math.min(res, arr[i]);``        ``}``    ``}` `    ``// Return the result``    ``return` `res;``}` `// Driver function``let arr = [ 1, 3, 5, 2, 4, 6 ];``let K = 2;``let N = arr.length;` `// Function call``console.log(ChooseNumber(arr, K, N));` `// this code is contributed by ksam24000`

Output

`1`

Time Complexity: O(N) where N is the size of the array
Auxiliary Space: O(N)

Another Approach: Using Hashmap

• Start the function ChooseNumber with input arguments arr, k, and n.
• Create an empty unordered_map called freq to store the frequency of each residue mod k.
• Initialize variables max_freq and res to 0.
• Loop through the input array arr from index 0 to n-1:
a. Calculate the residue of the current element mod k and store it in variable r.
b. Increment the frequency of r in freq.
c. If the frequency of r in freq is greater than max_freq, update max_freq to the new frequency and update res to r.
• If res is 0, all elements in arr are divisible by k, so return 0.
• Otherwise, return k – res, which is the smallest possible value of X that satisfies the condition.

## C++

 `#include ``#include ` `using` `namespace` `std;` `int` `ChooseNumber(``int` `arr[], ``int` `k, ``int` `n) {``    ``unordered_map<``int``, ``int``> freq;``    ``int` `max_freq = 0, res = 0;` `    ``for` `(``int` `i = 0; i < n; i++) {``        ``int` `r = arr[i] % k;``        ``freq[r]++;``        ``if` `(freq[r] > max_freq) {``            ``max_freq = freq[r];``            ``res = r;``        ``}``    ``}` `    ``if` `(res == 0) ``return` `0; ``// edge case where all elements are divisible by k` `    ``return` `(k - res);``}` `int` `main() {``    ``int` `arr[] = {1, 3, 5, 2, 4, 6};``    ``int` `k = 2;``    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr[0]);``    ``int` `ans = ChooseNumber(arr, k, n);``    ``cout << ans << endl; ``// output: 1``    ``return` `0;``}`

## Java

 `import` `java.util.*;` `public` `class` `Main {` `    ``// This function takes an array arr, an integer k, and the size of the array n as input``    ``// It returns an integer which is the number to be chosen``    ``public` `static` `int` `chooseNumber(``int``[] arr, ``int` `k, ``int` `n)``    ``{``      ` `        ``// Create a HashMap to store the frequency of the remainders of the elements in the array``        ``Map freq = ``new` `HashMap<>();``      ` `        ``// Initialize variables maxFreq and res``        ``int` `maxFreq = ``0``, res = ``0``;` `        ``// Loop through the array``        ``for` `(``int` `i = ``0``; i < n; i++)``        ``{``          ` `            ``// Calculate the remainder of the ith element in the array divided by k``            ``int` `r = arr[i] % k;``          ` `            ``// Increment the frequency of r in the HashMap``            ``freq.put(r, freq.getOrDefault(r, ``0``) + ``1``);``          ` `            ``// If the frequency of r is greater than maxFreq, update maxFreq and res``            ``if` `(freq.get(r) > maxFreq) {``                ``maxFreq = freq.get(r);``                ``res = r;``            ``}``        ``}` `        ``// If all elements in the array are divisible by k, return 0``        ``if` `(res == ``0``) ``return` `0``;` `        ``// Return k minus the chosen number``        ``return` `(k - res);``    ``}` `    ``public` `static` `void` `main(String[] args)``    ``{``      ` `        ``// Initialize the input array, k, and n``        ``int``[] arr = {``1``, ``3``, ``5``, ``2``, ``4``, ``6``};``        ``int` `k = ``2``;``        ``int` `n = arr.length;` `        ``// Call the chooseNumber function and store the result in ans``        ``int` `ans = chooseNumber(arr, k, n);` `        ``// Print the result``        ``System.out.println(ans); ``// output: 1``    ``}``}`

## Python3

 `from` `collections ``import` `defaultdict` `def` `ChooseNumber(arr, k, n):``    ``freq ``=` `defaultdict(``int``)``    ``max_freq ``=` `0``    ``res ``=` `0` `    ``for` `i ``in` `range``(n):``        ``r ``=` `arr[i] ``%` `k``        ``freq[r] ``+``=` `1``        ``if` `freq[r] > max_freq:``            ``max_freq ``=` `freq[r]``            ``res ``=` `r` `    ``if` `res ``=``=` `0``:``        ``return` `0` `# edge case where all elements are divisible by k` `    ``return` `k ``-` `res` `if` `__name__ ``=``=` `'__main__'``:``    ``arr ``=` `[``1``, ``3``, ``5``, ``2``, ``4``, ``6``]``    ``k ``=` `2``    ``n ``=` `len``(arr)``    ``ans ``=` `ChooseNumber(arr, k, n)``    ``print``(ans) ``# output: 1`

## C#

 `using` `System;``using` `System.Collections.Generic;` `class` `MainClass {``  ``public` `static` `int` `ChooseNumber(``int``[] arr, ``int` `k, ``int` `n)``  ``{``    ``Dictionary<``int``, ``int``> freq``      ``= ``new` `Dictionary<``int``, ``int``>();``    ``int` `max_freq = 0, res = 0;``    ``for` `(``int` `i = 0; i < n; i++) {``      ``int` `r = arr[i] % k;``      ``if` `(!freq.ContainsKey(r))``        ``freq[r] = 0;``      ``freq[r]++;``      ``if` `(freq[r] > max_freq) {``        ``max_freq = freq[r];``        ``res = r;``      ``}``    ``}` `    ``if` `(res == 0)``      ``return` `0; ``// edge case where all elements are``    ``// divisible by k` `    ``return` `(k - res);``  ``}` `  ``public` `static` `void` `Main()``  ``{``    ``int``[] arr = { 1, 3, 5, 2, 4, 6 };``    ``int` `k = 2;``    ``int` `n = arr.Length;``    ``int` `ans = ChooseNumber(arr, k, n);``    ``Console.WriteLine(ans); ``// output: 1``  ``}``}` `// This code is contributed by sarojmcy2e`

## Javascript

 `function` `ChooseNumber(arr, k, n) {``  ``const freq = ``new` `Map();``  ``let maxFreq = 0, res = 0;` `  ``for` `(let i = 0; i < n; i++) {``    ``const r = arr[i] % k;``    ``freq.set(r, (freq.get(r) || 0) + 1);``    ``if` `(freq.get(r) > maxFreq) {``      ``maxFreq = freq.get(r);``      ``res = r;``    ``}``  ``}` `  ``if` `(res === 0) ``return` `0; ``// edge case where all elements are divisible by k` `  ``return` `k - res;``}` `const arr = [1, 3, 5, 2, 4, 6];``const k = 2;``const n = arr.length;``const ans = ChooseNumber(arr, k, n);``console.log(ans); ``// output: 1`

Output

`1`

Time Complexity: O(N)
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up