Open In App

Kth Smallest Number in Multiplication Table

Last Updated : 03 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given three integers m, n, and k. Consider a grid of m * n, where mat[i][j] = i*j (1 based indexing). The task is to return the k'th smallest element in the m*n multiplication table.

Examples:

Input: m = 3, n = 3, k = 5
Output: 3
Explanation:

The 5th smallest element is 3. 

Input: m = 2, n = 3, k = 6
Output:
Explanation: [1, 2, 3][2, 4, 6]. The 6th smallest element is 6.

[Naive Approach] Checking all Possibilities - O(m*n * log(m*n)) time and O(m*n) space

The idea is to find the value of all possible combinations of i * j (where 1 <= i <= m and 1 <= j <= n), and insert these values into an array. Then, sort the array and return the k'th smallest element.

C++
// C++ program to find Kth Smallest
// Number in Multiplication Table
#include <bits/stdc++.h>
using namespace std;

int kthSmallest(int m, int n, int k) {
    vector<int> arr;
    
    // Try all combinations
    for (int i=1; i<=m; i++) {
        for (int j=1; j<=n; j++) {
            arr.push_back(i*j);
        }
    }
    
    // Sort the array 
    sort(arr.begin(), arr.end());
    
    return arr[k-1];
}

int main() {
    int m = 3, n = 3, k = 5;
    cout << kthSmallest(m, n, k);

    return 0;
}
Java
// Java program to find Kth Smallest
// Number in Multiplication Table
import java.util.*;

class GfG {

    static int kthSmallest(int m, int n, int k) {
        ArrayList<Integer> arr = new ArrayList<>();
        
        // Try all combinations
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                arr.add(i * j);
            }
        }
        
        // Sort the array 
        Collections.sort(arr);
        
        return arr.get(k - 1);
    }

    public static void main(String[] args) {
        int m = 3, n = 3, k = 5;
        System.out.println(kthSmallest(m, n, k));
    }
}
Python
# Python program to find Kth Smallest
# Number in Multiplication Table

def kthSmallest(m, n, k):
    arr = []
    
    # Try all combinations
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            arr.append(i * j)
    
    # Sort the array 
    arr.sort()
    
    return arr[k - 1]

if __name__ == "__main__":
    m = 3
    n = 3
    k = 5
    print(kthSmallest(m, n, k))
C#
// C# program to find Kth Smallest
// Number in Multiplication Table
using System;
using System.Collections.Generic;

class GfG {

    static int kthSmallest(int m, int n, int k) {
        List<int> arr = new List<int>();
        
        // Try all combinations
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                arr.Add(i * j);
            }
        }
        
        // Sort the array 
        arr.Sort();
        
        return arr[k - 1];
    }

    static void Main(string[] args) {
        int m = 3, n = 3, k = 5;
        Console.WriteLine(kthSmallest(m, n, k));
    }
}
JavaScript
// JavaScript program to find Kth Smallest
// Number in Multiplication Table

function kthSmallest(m, n, k) {
    let arr = [];
    
    // Try all combinations
    for (let i = 1; i <= m; i++) {
        for (let j = 1; j <= n; j++) {
            arr.push(i * j);
        }
    }
    
    // Sort the array 
    arr.sort((a, b) => a - b);
    
    return arr[k - 1];
}

let m = 3, n = 3, k = 5;
console.log(kthSmallest(m, n, k));

Output
3

[Better Approach] Using Max Heap - O(m*n * log(k)) time and O(k) space

The idea is similar to kth Smallest Element using Max Heap. We generate all values of the form (i * j) and maintain a max heap of size k. If the current element is smaller than the largest element in our heap, we replace the largest element with the current one. At the end, the Max Heap root contains kth smallest values.

Step by step approach:

  1. Create a max heap data structure to store k smallest elements.
  2. Iterate through all cells in the m*n table.
  3. Add elements to the heap until it reaches size k.
  4. For subsequent elements, if smaller than heap top, replace the largest element.
  5. Return the top element of the heap which is the kth smallest.
C++
// C++ program to find Kth Smallest
// Number in Multiplication Table
#include <bits/stdc++.h>
using namespace std;

int kthSmallest(int m, int n, int k) {
	priority_queue<int> pq;
	
	// Check all combinations
	for (int i=1; i<=m; i++) {
		for (int j=1; j<=n; j++) {
		    
		    // If size of heap is less 
		    // than k.
			if (pq.size() < k) {
				pq.push(i*j);
			}
			
			// Else if current value is 
			// less than heap top.
			else if (i*j < pq.top()) {
				pq.pop();
				pq.push(i*j);
			}
		}
	}

	return pq.top();
}

int main() {
	int m = 3, n = 3, k = 5;
	cout << kthSmallest(m, n, k);

	return 0;
}
Java
// Java program to find Kth Smallest
// Number in Multiplication Table
import java.util.*;

class GfG {

    static int kthSmallest(int m, int n, int k) {
        PriorityQueue<Integer> pq = 
        new PriorityQueue<>(Collections.reverseOrder());

        // Check all combinations
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {

                // If size of heap is less 
                // than k.
                if (pq.size() < k) {
                    pq.add(i * j);
                }

                // Else if current value is 
                // less than heap top.
                else if (i * j < pq.peek()) {
                    pq.poll();
                    pq.add(i * j);
                }
            }
        }

        return pq.peek();
    }

    public static void main(String[] args) {
        int m = 3, n = 3, k = 5;
        System.out.println(kthSmallest(m, n, k));
    }
}
Python
# Python program to find Kth Smallest
# Number in Multiplication Table
import heapq

def kthSmallest(m, n, k):
    pq = []

    # Check all combinations
    for i in range(1, m + 1):
        for j in range(1, n + 1):

            # If size of heap is less 
            # than k.
            if len(pq) < k:
                heapq.heappush(pq, -(i * j))

            # Else if current value is 
            # less than heap top.
            elif i * j < -pq[0]:
                heapq.heappop(pq)
                heapq.heappush(pq, -(i * j))

    return -pq[0]

if __name__ == "__main__":
    m = 3
    n = 3
    k = 5
    print(kthSmallest(m, n, k))
C#
// C# program to find Kth Smallest
// Number in Multiplication Table
using System;
using System.Collections.Generic;

class GfG {

    static int kthSmallest(int m, int n, int k) {
        PriorityQueue<int> pq = new PriorityQueue<int>(new Comparer());

        // Check all combinations
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {

                // If size of heap is less 
                // than k.
                if (pq.Count < k) {
                    pq.Enqueue(i * j);
                }

                // Else if current value is 
                // less than heap top.
                else if (i * j < pq.Peek()) {
                    pq.Dequeue();
                    pq.Enqueue(i * j);
                }
            }
        }

        return pq.Peek();
    }

    static void Main(string[] args) {
        int m = 3, n = 3, k = 5;
        Console.WriteLine(kthSmallest(m, n, k));
    }
}

// Custom comparator class for max heap
class Comparer : IComparer<int> {
    public int Compare(int a, int b) {
        if (a < b)
            return 1;
        else if (a > b)
            return -1;
        return 0;
    }
}

// Custom Priority queue 
class PriorityQueue<T> {
    private List<T> heap;
    private IComparer<T> comparer;

    public PriorityQueue(IComparer<T> comparer = null) {
        this.heap = new List<T>();
        this.comparer = comparer ?? Comparer<T>.Default;
    }

    public int Count => heap.Count;

    // Enqueue operation
    public void Enqueue(T item) {
        heap.Add(item);
        int i = heap.Count - 1;
        while (i > 0) {
            int parent = (i - 1) / 2;
            if (comparer.Compare(heap[parent], heap[i]) <= 0)
                break;
            Swap(parent, i);
            i = parent;
        }
    }

    // Dequeue operation
    public T Dequeue() {
        if (heap.Count == 0)
            throw new InvalidOperationException("Priority queue is empty.");
        T result = heap[0];
        int last = heap.Count - 1;
        heap[0] = heap[last];
        heap.RemoveAt(last);
        last--;
        int i = 0;
        while (true) {
            int left = 2 * i + 1;
            if (left > last)
                break;
            int right = left + 1;
            int minChild = left;
            if (right <= last && comparer.Compare(heap[right], heap[left]) < 0)
                minChild = right;
            if (comparer.Compare(heap[i], heap[minChild]) <= 0)
                break;
            Swap(i, minChild);
            i = minChild;
        }
        return result;
    }

    public T Peek() {
        if (heap.Count == 0)
            throw new InvalidOperationException("Priority queue is empty.");
        return heap[0];
    }

    private void Swap(int i, int j) {
        T temp = heap[i];
        heap[i] = heap[j];
        heap[j] = temp;
    }
}
JavaScript
// JavaScript program to find Kth Smallest
// Number in Multiplication Table

function kthSmallest(m, n, k) {
	let pq = new PriorityQueue(Comparator);

	// Check all combinations
	for (let i = 1; i <= m; i++) {
		for (let j = 1; j <= n; j++) {

			// If size of heap is less 
			// than k.
			if (pq.heap.length < k) {
				pq.enqueue(i * j);
			}

			// Else if current value is 
			// less than heap top.
			else if (i * j < pq.peek()) {
				pq.dequeue();
				pq.enqueue(i * j);
			}
		}
	}

	return pq.peek();
}

// Comparator function to compare data
function Comparator(a, b) {
	if (a > b) return 1;
	if (a < b) return -1;
	return 0;
}

class PriorityQueue {
	constructor(compare) {
		this.heap = [];
		this.compare = compare;
	}

	enqueue(value) {
		this.heap.push(value);
		this.bubbleUp();
	}

	bubbleUp() {
		let index = this.heap.length - 1;
		while (index > 0) {
			let element = this.heap[index],
			    parentIndex = Math.floor((index - 1) / 2),
			    parent = this.heap[parentIndex];
			if (this.compare(element, parent) < 0) break;
			this.heap[index] = parent;
			this.heap[parentIndex] = element;
			index = parentIndex;
		}
	}

	dequeue() {
		let max = this.heap[0];
		let end = this.heap.pop();
		if (this.heap.length > 0) {
			this.heap[0] = end;
			this.sinkDown(0);
		}
		return max;
	}

	peek() {
		return this.heap[0];
	}

	sinkDown(index) {
		let left = 2 * index + 1,
		    right = 2 * index + 2,
		    largest = index;

		if (
		    left < this.heap.length &&
		    this.compare(this.heap[left], this.heap[largest]) > 0
		) {
			largest = left;
		}

		if (
		    right < this.heap.length &&
		    this.compare(this.heap[right], this.heap[largest]) > 0
		) {
			largest = right;
		}

		if (largest !== index) {
			[this.heap[largest], this.heap[index]] = [
			            this.heap[index],
			            this.heap[largest],
			        ];
			this.sinkDown(largest);
		}
	}

	isEmpty() {
		return this.heap.length === 0;
	}
}

let m = 3, n = 3, k = 5;
console.log(kthSmallest(m, n, k));

Output
3

[Expected Approach] Using Binary Search - O(m * log (m*n)) time and O(1) space

The idea is to use binary search to find the kth smallest number in the multiplication table. Instead of generating all m*n elements, we define the search range from 1 to m*n and use binary search to find the value where exactly k elements in the table are smaller than or equal to it. We count smaller values than the current mid value. If the count is more than k, we go the right half, else we go the left half.

How can we count values less than equal to x?

To count values less than or equal to a given number x in the multiplication table, we iterate through each row i from 1 to m and count how many elements in that row are less than or equal to x. For each row i, the elements are i, 2i, 3i, ..., n*i, so there are min(x/i, n) such elements in row i.

C++
// C++ program to find Kth Smallest
// Number in Multiplication Table
#include <bits/stdc++.h>
using namespace std;

// Function to find the number of 
// values less than equal to val.
int count(int val, int m, int n) {
	int cnt = 0;
	for (int i = 1; i <= m; ++i) {
		cnt += min(val / i, n);
	}
	return cnt;
};

int kthSmallest(int m, int n, int k) {
    
	// Binary search to find the kth number
	int l = 1, h = m * n;
	while (l < h) {
		int mid = (l + h) / 2;
		if (count(mid, m, n) < k) {
			l = mid + 1;
		} else {
			h = mid;
		}
	}
	
	// Return the kth smallest number
	return l; 
}

int main() {
	int m = 3, n = 3, k = 5;
	cout << kthSmallest(m, n, k);

	return 0;
}
Java
// Java program to find Kth Smallest
// Number in Multiplication Table

class GfG {

    // Function to find the number of 
    // values less than equal to val.
    static int count(int val, int m, int n) {
        int cnt = 0;
        for (int i = 1; i <= m; ++i) {
            cnt += Math.min(val / i, n);
        }
        return cnt;
    }

    static int kthSmallest(int m, int n, int k) {

        // Binary search to find the kth number
        int l = 1, h = m * n;
        while (l < h) {
            int mid = (l + h) / 2;
            if (count(mid, m, n) < k) {
                l = mid + 1;
            } else {
                h = mid;
            }
        }

        // Return the kth smallest number
        return l; 
    }

    public static void main(String[] args) {
        int m = 3, n = 3, k = 5;
        System.out.println(kthSmallest(m, n, k));
    }
}
Python
# Python program to find Kth Smallest
# Number in Multiplication Table

# Function to find the number of 
# values less than equal to val.
def count(val, m, n):
    cnt = 0
    for i in range(1, m + 1):
        cnt += min(val // i, n)
    return cnt

def kthSmallest(m, n, k):

    # Binary search to find the kth number
    l, h = 1, m * n
    while l < h:
        mid = (l + h) // 2
        if count(mid, m, n) < k:
            l = mid + 1
        else:
            h = mid

    # Return the kth smallest number
    return l

if __name__ == "__main__":
    m = 3
    n = 3
    k = 5
    print(kthSmallest(m, n, k))
C#
// C# program to find Kth Smallest
// Number in Multiplication Table
using System;

class GfG {

    // Function to find the number of 
    // values less than equal to val.
    static int count(int val, int m, int n) {
        int cnt = 0;
        for (int i = 1; i <= m; ++i) {
            cnt += Math.Min(val / i, n);
        }
        return cnt;
    }

    static int kthSmallest(int m, int n, int k) {

        // Binary search to find the kth number
        int l = 1, h = m * n;
        while (l < h) {
            int mid = (l + h) / 2;
            if (count(mid, m, n) < k) {
                l = mid + 1;
            } else {
                h = mid;
            }
        }

        // Return the kth smallest number
        return l; 
    }

    static void Main(string[] args) {
        int m = 3, n = 3, k = 5;
        Console.WriteLine(kthSmallest(m, n, k));
    }
}
JavaScript
// JavaScript program to find Kth Smallest
// Number in Multiplication Table

// Function to find the number of 
// values less than equal to val.
function count(val, m, n) {
	let cnt = 0;
	for (let i = 1; i <= m; ++i) {
		cnt += Math.min(Math.floor(val / i), n);
	}
	return cnt;
}

function kthSmallest(m, n, k) {

	// Binary search to find the kth number
	let l = 1, h = m * n;
	while (l < h) {
		let mid = Math.floor((l + h) / 2);
		if (count(mid, m, n) < k) {
			l = mid + 1;
		} else {
			h = mid;
		}
	}

	// Return the kth smallest number
	return l; 
}

let m = 3, n = 3, k = 5;
console.log(kthSmallest(m, n, k));

Output
3

Next Article

Similar Reads