1. Permutation Generation (Brute Force)
Intuition
There are n! possible arrangements of n numbers. We can recursively construct all n! permutations, concatenate them into a full number string, and update the global maximum using lexicographical comparison.
When to apply: Use only for conceptual validation on tiny inputs (n <= 8).
All Permutations Concatenation (O(N!) Time)
2 of 2 questions left todayFirst permutation candidate
First permutation candidate.
import java.util.*; public class Main { public static class Solution { private String maxNum = "0"; public String largestNumber(int[] nums) { String[] strs = new String[nums.length]; for (int i = 0; i < nums.length; i++) strs[i] = String.valueOf(nums[i]); permute(strs, 0); return maxNum.charAt(0) == '0' ? "0" : maxNum; } private void permute(String[] strs, int idx) { if (idx == strs.length) { StringBuilder sb = new StringBuilder(); for (String s : strs) sb.append(s); String cand = sb.toString(); if (maxNum.equals("0") || cand.compareTo(maxNum) > 0) { maxNum = cand; } return; } for (int i = idx; i < strs.length; i++) { swap(strs, idx, i); permute(strs, idx + 1); swap(strs, idx, i); } } private void swap(String[] strs, int i, int j) { String temp = strs[i]; strs[i] = strs[j]; strs[j] = temp; } } public static void main(String[] args) { Solution sol = new Solution(); int[] nums = {3, 30, 34, 5, 9}; System.out.println("Largest Number: " + sol.largestNumber(nums)); }}Time & Space Complexity
- Time complexity:
O(n! * n * k)— Generating all n! permutations and building concatenated strings of length n * k takes O(n! * n * k) time. - Space complexity:
O(n * k)— Recursion depth and string buffers take O(n * k) memory.
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.