Post #500: don't assume that 2 nested loops == O(N^2)

Wow, post #500 :)

This is an easy LC problem. It is interesting that the solution requires only counting the number of occurrences of each digits, storing in a small array, and then using that to create the largest value. If you can see the implementation, it shows two nested loops, but upon a closer look into the implementation, you'll notice that the outer loop executes in O(LogN) where N is the input number, and the nested loops cannot go beyond 10 steps no matter what, hence the overall Big-O time becomes O(LogN) despite the N^2-like implementation. Code is down below, cheers, ACC.

Largest Number After Digit Swaps by Parity - LeetCode

2231. Largest Number After Digit Swaps by Parity
Easy

You are given a positive integer num. You may swap any two digits of num that have the same parity (i.e. both odd digits or both even digits).

Return the largest possible value of num after any number of swaps.

 

Example 1:

Input: num = 1234
Output: 3412
Explanation: Swap the digit 3 with the digit 1, this results in the number 3214.
Swap the digit 2 with the digit 4, this results in the number 3412.
Note that there may be other sequences of swaps but it can be shown that 3412 is the largest possible number.
Also note that we may not swap the digit 4 with the digit 1 since they are of different parities.

Example 2:

Input: num = 65875
Output: 87655
Explanation: Swap the digit 8 with the digit 6, this results in the number 85675.
Swap the first digit 5 with the digit 7, this results in the number 87655.
Note that there may be other sequences of swaps but it can be shown that 87655 is the largest possible number.

 

Constraints:

  • 1 <= num <= 109

public int LargestInteger(int num)
{
    string str = num.ToString();

    int[] count = new int[10];
    foreach (char c in str) count[(int)(c - '0')]++;

    string retVal = "";
    int pEven = count.Length - 1;
    int pOdd = count.Length - 1;

    for (int i = 0; i < str.Length; i++)
    {
        int n = (int)(str[i] - '0');
        if (n % 2 == 0)
        {
            while (pEven >= 0 && (pEven % 2 == 1 || count[pEven] <= 0)) pEven--;
            retVal += pEven.ToString();
            count[pEven]--;
        }
        else
        {
            while (pOdd >= 0 && (pOdd % 2 == 0 || count[pOdd] <= 0)) pOdd--;
            retVal += pOdd.ToString();
            count[pOdd]--;
        }
    }

    return Int32.Parse(retVal);
}

Comments

Popular posts from this blog

Advent of Code - Day 6, 2024: BFS and FSM

Golang vs. C#: performance characteristics (simple case study)

Advent of Code - Day 7, 2024: Backtracking and Eval