703498. Smallest number repeating K times

Basic

Here is a detailed Markdown blog post for the problem "Smallest number repeating K times":

Smallest number repeating K times

Summary

The problem involves finding the smallest number that, when repeated k times, will result in a specific sum. This problem can be approached using basic algorithmic concepts such as arrays and hash data structures.

Detailed Explanation

To solve this problem, we need to generate all numbers from 1 to n (where n is the given input) and find the smallest number that, when repeated k times, will result in a specific sum. We can use an array to store these generated numbers and their corresponding counts. Then, we iterate over the array to find the smallest number that meets our condition.

Here's a step-by-step breakdown of the solution:

  1. Initialize an empty hash map countMap to store the count of each number from 1 to n.
  2. Iterate through the range from 1 to n and for each number, increment its count in the countMap.
  3. Initialize a variable smallestNumber to store the smallest number that meets our condition.
  4. Iterate over the countMap to find the smallest number that, when repeated k times, will result in the specific sum.
  5. For each number and its count, check if multiplying the number by k and adding it to the current total equals the specific sum. If yes, update smallestNumber.
  6. Return smallestNumber.

Time complexity: O(n) Space complexity: O(n)

Optimized Solutions

Java

java
public class SmallestNumberRepeatingKTimes {
    public static int findSmallest(int n, int k, int sum) {
        int smallest = 0;
        for (int i = 1; i <= n; i++) {
            int count = 0;
            while ((i * k) + count <= sum) {
                count += i * k;
            }
            if (count == sum) {
                smallest = i;
                break;
            }
        }
        return smallest;
    }
}

Python

python
def find_smallest(n, k, sum):
    for i in range(1, n + 1):
        count = 0
        while (i * k) + count <= sum:
            count += i * k
        if count == sum:
            return i
    return 0

C++

cpp
#include <iostream>
int findSmallest(int n, int k, int sum) {
    for (int i = 1; i <= n; i++) {
        int count = 0;
        while ((i * k) + count <= sum) {
            count += i * k;
        }
        if (count == sum) {
            return i;
        }
    }
    return 0;
}

JavaScript

javascript
function findSmallest(n, k, sum) {
    for (let i = 1; i <= n; i++) {
        let count = 0;
        while ((i * k) + count <= sum) {
            count += i * k;
        }
        if (count == sum) {
            return i;
        }
    }
    return 0;
}
View on GeeksforGeeks

Not available

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.