713146. Count Lucky Permutations

Hard

Count Lucky Permutations

Summary

Given a string s containing only digits, we need to count the number of lucky permutations. A permutation is considered "lucky" if the sum of its digits is equal to the length of the permutation. For example, for the string "123", there are 3! (6) permutations: "123", "132", "213", "231", "312", and "321". Out of these, only two permutations ("123" and "132") have a digit sum equal to their length (i.e., 1 + 2 + 3 = 6), so the count is 2. This problem involves dynamic programming concepts.

Detailed Explanation

The approach here is to use dynamic programming to solve this problem. We'll create a 2D array dp where dp[i][j] represents the number of lucky permutations for the first i digits, ending with digit j.

Here's the step-by-step breakdown:

  1. Initialize the dp array: dp[0][0] = 1, because there is only one way to get a lucky permutation for an empty string (which has length 0).
  2. Fill up the first row of dp: dp[i][j] = 0 for all i > 0 and j. This is because we can't have a lucky permutation starting with digit j if there are less than j+1 digits.
  3. For each pair (i, j) where i > 0, calculate the number of lucky permutations ending with j:
    • If j == 0, then the sum of the last digit is equal to the length (i.e., 1), so we add the value in dp[i-1][0] to the result.
    • Otherwise, for each possible next digit k, check if the sum of its digits is equal to the new length (i+1). If yes, then add the value in dp[i-1][k] to the result.
  4. Finally, return the sum of all values in the last row of dp.

Time complexity: O(n), where n is the number of digits in the input string. This is because we only iterate over each digit once.

Space complexity: O(n), as we need to store the dp array.

Optimized Solutions

Java

View on GeeksforGeeks
public int countLuckyPermutations(String s) {
    int n = s.length();
    int[] dp = new int[n + 1];
    dp[0] = 1;
    
    for (int i = 1; i <= n; i++) {
        for (int j = 0; j < 10; j++) {
            if (i > 0 || j == 0) {
                int sum = 0;
                for (int k = 0; k < i; k++) {
                    sum += s.charAt(k) - '0';
                }
                sum += j;
                if (sum == i) {
                    dp[i] += dp[i - 1];
                }
            }
        }
    }
    
    return dp[n];
}

DevExCode

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

© 2026 DevExCode. All rights reserved.