Problem solution · Java

Count Number of Balanced Permutations

Count Number of Balanced Permutations: a Java solution using sorting and greedy selection. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Sorting and greedy selection
Source
walkccc LeetCode Solutions
Length
100 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Sorting and greedy selection

For Count Number of Balanced Permutations, the implementation first exposes a useful order, then scans that order while making locally justified choices.

  1. Choose the key that reveals the greedy or grouping structure.
  2. Sort the relevant records by that key.
  3. Scan in order, maintaining the invariant that makes each local choice safe.

Code notes

  • 100 lines of Java from the credited upstream file 3343.java.
  • The implementation visibly relies on sequence storage.
  • 7 loop blocks detected.

Complexity

Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeCount Number of Balanced Permutations · JavaJava
Use this to learn the idea, then write your own version.
class Solution {  public int countBalancedPermutations(String num) {    int[] nums = getNums(num);    final int sum = Arrays.stream(nums).sum();    if (sum % 2 == 1)      return 0;     Arrays.sort(nums);    reverse(nums, 0, nums.length - 1);     final int even = (nums.length + 1) / 2;    final int odd = nums.length / 2;    final int evenBalance = sum / 2;    Long[][][] mem = new Long[even + 1][odd + 1][evenBalance + 1];    final long perm = getPerm(nums);    return (        int) ((countBalancedPermutations(nums, even, odd, evenBalance, mem) * modInverse(perm)) %              MOD);  }   private static final int MOD = 1_000_000_007;   // Returns the number of permutations where there are `even` even indices  // left, `odd` odd indices left, and `evenBalance` is the target sum of the  // remaining numbers to be placed in even indices.  private long countBalancedPermutations(int[] nums, int even, int odd, int evenBalance,                                         Long[][][] mem) {    if (evenBalance < 0)      return 0;    if (even == 0)      return evenBalance == 0 ? factorial(odd) : 0;    final int index = nums.length - (even + odd);    if (odd == 0) {      long remainingSum = 0;      for (int i = index; i < nums.length; ++i)        remainingSum += nums[i];      return remainingSum == evenBalance ? factorial(even) : 0;    }    if (mem[even][odd][evenBalance] != null)      return mem[even][odd][evenBalance];    final long placeEven =        countBalancedPermutations(nums, even - 1, odd, evenBalance - nums[index], mem) * even % MOD;    final long placeOdd =        countBalancedPermutations(nums, even, odd - 1, evenBalance, mem) * odd % MOD;    return mem[even][odd][evenBalance] = (placeEven + placeOdd) % MOD;  }   private int[] getNums(String num) {    int[] nums = new int[num.length()];    for (int i = 0; i < num.length(); ++i)      nums[i] = num.charAt(i) - '0';    return nums;  }   private long getPerm(int[] nums) {    long res = 1;    int[] count = new int[10];    for (final int num : nums)      ++count[num];    for (final int freq : count)      res = res * factorial(freq) % MOD;    return res;  }   private long factorial(int n) {    long res = 1;    for (int i = 2; i <= n; ++i)      res = res * i % MOD;    return res;  }   private long modInverse(long a) {    long m = MOD;    long y = 0;    long x = 1;    while (a > 1) {      final long q = a / m;      long t = m;      m = a % m;      a = t;      t = y;      y = x - q * y;      x = t;    }     return x < 0 ? x + MOD : x;  }   private void reverse(int[] nums, int l, int r) {    while (l < r)      swap(nums, l++, r--);  }   private void swap(int[] nums, int i, int j) {    final int temp = nums[i];    nums[i] = nums[j];    nums[j] = temp;  }} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗