Problem solution · Java

Unique 3-Digit Even Numbers

Unique 3-Digit Even Numbers: 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
56 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 Unique 3-Digit Even Numbers, 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

  • 56 lines of Java from the credited upstream file 3483.java.
  • The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
  • 4 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 codeUnique 3-Digit Even Numbers · JavaJava
Use this to learn the idea, then write your own version.
class Solution {  public int totalNumbers(int[] digits) {    Set<Integer> nums = new HashSet<>();    int[] perm = digits.clone();     Arrays.sort(perm);     do {      final int a = perm[0];      final int b = perm[1];      final int c = perm[2];      if (a != 0 && c % 2 == 0) {        nums.add(a * 100 + b * 10 + c);      }    } while (nextPermutation(perm));     return nums.size();  }   private boolean nextPermutation(int[] nums) {    final int n = nums.length;     // From the back to the front, find the first num < nums[i + 1].    int i;    for (i = n - 2; i >= 0; --i)      if (nums[i] < nums[i + 1])        break;     if (i < 0)      return false;     // From the back to the front, find the first num > nums[i] and swap it with    // nums[i].    for (int j = n - 1; j > i; --j)      if (nums[j] > nums[i]) {        swap(nums, i, j);        break;      }     // Reverse nums[i + 1..n - 1].    reverse(nums, i + 1, n - 1);    return true;  }   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 ↗