Find X such that most Array elements are of form (X + p*K)
Last Updated :
27 Apr, 2023
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++
#include <bits/stdc++.h>
using namespace std;
int ChooseNumber( int arr[], int k, int n)
{
unordered_map< int , int > m;
int res = INT_MAX;
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];
}
for ( int i = 0; i < n; i++) {
if (max_rem == m[arr[i] % k]) {
res = min(res, arr[i]);
}
}
return res;
}
int main()
{
int arr[] = { 1, 3, 5, 2, 4, 6 };
int K = 2;
int N = sizeof (arr) / sizeof (arr[0]);
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)
{
HashMap<Integer, Integer> m = new HashMap<>();
int res = Integer.MAX_VALUE;
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 );
}
for ( int i = 0 ; i < n; i++) {
if (max_rem == m.getOrDefault(arr[i] % k, 0 )) {
res = Math.min(res, arr[i]);
}
}
return res;
}
public static void main(String[] args)
{
int [] arr = { 1 , 3 , 5 , 2 , 4 , 6 };
int K = 2 ;
int N = 6 ;
System.out.println(ChooseNumber(arr, K, N));
}
}
|
Python3
def ChooseNumber(arr, k, n):
m = {}
for i in range (n + 1 ):
m[i] = 0
res = 1e9
max_rem = - 1e9
for i in range (n):
rem = arr[i] % k
m[rem] + = 1
if (max_rem < m[rem]):
max_rem = m[rem]
for i in range (n):
if (max_rem = = m[arr[i] % k]):
res = min (res, arr[i])
return res
arr = [ 1 , 3 , 5 , 2 , 4 , 6 ]
K = 2
N = len (arr)
print (ChooseNumber(arr, K, N))
|
C#
using System;
using System.Collections.Generic;
class GFG {
static int ChooseNumber( int [] arr, int k, int n)
{
Dictionary< int , int > m = new Dictionary< int , int >();
int res = Int32.MaxValue;
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);
}
for ( int i = 0; i < n; i++) {
if (max_rem
== m.GetValueOrDefault(arr[i] % k, 0)) {
res = Math.Min(res, arr[i]);
}
}
return res;
}
public static void Main()
{
int [] arr = { 1, 3, 5, 2, 4, 6 };
int K = 2;
int N = 6;
Console.WriteLine(ChooseNumber(arr, K, N));
}
}
|
Javascript
function ChooseNumber(arr, k, n)
{
let m = {};
for (let i = 0; i < n + 1; i++)
{
m[i] = 0;
}
let res = Number.MAX_VALUE;
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];
}
for (let i = 0; i < n; i++) {
if (max_rem == m[arr[i] % k]) {
res = Math.min(res, arr[i]);
}
}
return res;
}
let arr = [ 1, 3, 5, 2, 4, 6 ];
let K = 2;
let N = arr.length;
console.log(ChooseNumber(arr, K, N));
|
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 <iostream>
#include <unordered_map>
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;
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;
return 0;
}
|
Java
import java.util.*;
public class Main {
public static int chooseNumber( int [] arr, int k, int n)
{
Map<Integer, Integer> freq = new HashMap<>();
int maxFreq = 0 , res = 0 ;
for ( int i = 0 ; i < n; i++)
{
int r = arr[i] % k;
freq.put(r, freq.getOrDefault(r, 0 ) + 1 );
if (freq.get(r) > maxFreq) {
maxFreq = freq.get(r);
res = r;
}
}
if (res == 0 ) return 0 ;
return (k - res);
}
public static void main(String[] args)
{
int [] arr = { 1 , 3 , 5 , 2 , 4 , 6 };
int k = 2 ;
int n = arr.length;
int ans = chooseNumber(arr, k, n);
System.out.println(ans);
}
}
|
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
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)
|
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;
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);
}
}
|
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;
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);
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...