1. Increment and Digits Comparison (Brute Force)
Intuition
Count the frequency of each digit 0-9 in the number n. Increment candidate = n + 1, n + 2, ... and count digit frequencies. If the digit counts match, we found the smallest greater integer with identical digits. If candidate exceeds Integer.MAX_VALUE (2147483647), return -1.
When to apply: Use only for small numbers to understand the digit permutation requirement.
Brute Force Increment Trace
2 of 2 questions left todayGiven n = 12
Given n = 12. Digits: {1: 1, 2: 1}. Goal: find smallest number > 12 with digits 1 and 2.
public class Main { public static class Solution { public int nextGreaterElement(int n) { int[] count = getCount(n); long cand = (long)n + 1; while (cand <= Integer.MAX_VALUE) { if (matches(count, getCount(cand))) { return (int)cand; } cand++; } return -1; } private int[] getCount(long num) { int[] c = new int[10]; while (num > 0) { c[(int)(num % 10)]++; num /= 10; } return c; } private boolean matches(int[] a, int[] b) { for (int i = 0; i < 10; i++) { if (a[i] != b[i]) return false; } return true; } } public static void main(String[] args) { Solution sol = new Solution(); int n = 12; System.out.println("Next Greater Element: " + sol.nextGreaterElement(n)); }}Time & Space Complexity
- Time complexity:
O(k * d)— Checking up to k integers where each integer takes d digit frequency checks takes O(k * d) time. - Space complexity:
O(1)— O(1) auxiliary frequency arrays of fixed size 10.
Why Brute Force Doesn't Scale:
For N = 105, quadratic O(N2) approaches require ~1010 operations, exceeding the standard 1-second CPU budget.
The optimal approach processes N elements in a single or logarithmic pass, completing in under 10ms with minimal memory footprint.