Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Find a number K such that exactly K array elements are greater than or equal to K
Next article icon

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

Last Updated : 26 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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 <bits/stdc++.h> 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<Integer, Integer> 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 <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; // 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<Integer, Integer> 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) 


Next Article
Find a number K such that exactly K array elements are greater than or equal to K

L

lokeshpotta20
Improve
Article Tags :
  • Mathematical
  • Hash
  • Technical Scripter
  • DSA
  • Technical Scripter 2022
Practice Tags :
  • Hash
  • Mathematical

Similar Reads

  • Find the number of elements X such that X + K also exists in the array
    Given an array a[] and an integer k, find the number of elements x in this array such that the sum of x and k is also present in the array. Examples: Input: { 3, 6, 2, 8, 7, 6, 5, 9 } and k = 2Output: 5 Explanation:Elements {3, 6, 7, 6, 5} in this array have x + 2 value that is{5, 8, 9, 8, 7} presen
    10 min read
  • Find K for every Array element such that at least K prefixes are ≥ K
    Given an array arr[] consisting of N non-negative integers, the task is to find an integer K for every index such that at least K integers in the array till that index are greater or equal to K. Note: Consider 1-based indexing Examples: Input: arr[] = {3, 0, 6, 1, 5} Output: K = {1, 1, 2, 2, 3} Expl
    7 min read
  • Find the most frequent element K positions apart from X in given Array
    Given an array nums[], and integer K and X, the task is to find the most frequent element K positions away from X in the given array. Examples: Input: nums = [1, 100, 200, 1, 100], K = 1, X = 1Output: 100Explanation: Elements 1 position apart from 1 is only 100.So the answer is 100. Input: nums = [2
    6 min read
  • Maximum value K such that array has at-least K elements that are >= K
    Given an array of positive integers, find maximum possible value K such that the array has at-least K elements that are greater than or equal to K. The array is unsorted and may contain duplicate values. Examples : Input: [2, 3, 4, 5, 6, 7] Output: 4 Explanation : 4 elements [4, 5, 6, 7] are greater
    14 min read
  • Find a number K such that exactly K array elements are greater than or equal to K
    Given an array a[] of size N, which contains only non-negative elements, the task is to find any integer K for which there are exactly K array elements that are greater than or equal to K. If no such K exists, then print -1. Examples: Input: a[] = {7, 8, 9, 0, 0, 1}Output: 3Explanation:Since 3 is le
    10 min read
  • Find four elements that sum to a given value | Set 3 (Hashmap)
    Given an array of integers, Check if there exist four elements at different indexes in the array whose sum is equal to a given value k. For example, if the given array is {1 5 1 0 6 0} and k = 7, then your function should print "YES" as (1+5+1+0=7). Examples: Input : arr[] = {1 5 1 0 6 0} k = 7 Outp
    7 min read
  • Remove elements from the array which appear more than k times
    Given an array of integers, remove all the occurrences of those elements which appear strictly more than k times in the array.Examples: Input : arr[] = {1, 2, 2, 3, 2, 3, 4} k = 2Output : 1 3 3 4Input : arr[] = {2, 5, 5, 7} k = 1Output : 2 7Approach: Take a hash map, which will store the frequency o
    8 min read
  • Maximize number of elements from Array with sum at most K
    Given an array A[] of N integers and an integer K, the task is to select the maximum number of elements from the array whose sum is at most K. Examples: Input: A[] = {1, 12, 5, 111, 200, 1000, 10}, K = 50 Output: 4 Explanation: Maximum number of selections will be 1, 12, 5, 10 that is 1 + 12 + 5 + 1
    6 min read
  • Find set of size K such that any value of the set is co-prime with any Array element
    Given a set S of having numbers 1, 2, 3, . . ., N, and an integer K, the task is to form a set A by taking K values from S such that any pair formed by taking one value from S and another from A, is always coprime. (Two numbers are coprime if their GCD is 1). Note: If multiple solutions exist, print
    10 min read
  • Minimum K such that sum of array elements after division by K does not exceed S
    Given an array arr[] of N elements and an integer S. The task is to find the minimum number K such that the sum of the array elements does not exceed S after dividing all the elements by K. Note: Consider integer division.Examples: Input: arr[] = {10, 7, 8, 10, 12, 19}, S = 27 Output: 3 After dividi
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences