Linearity based on bucketization

Common problems require a bucketization strategy in order to speed up the solution. It is a tradeoff between space and time. The problem below would naively require an N^2 approach. In order to speed it up, here is the approach:

1. Count the number of digits from 0..9 in each position of the number. Notice that there are 5 positions available (since the max number is 10^5).

2. At this point, for each position, do a nested loop (0..9, nested with 0..9) multiplying the ones that are different, and adding them to the result (use a long cast to avoid overflow)

The first step takes N. The second is quicker: 5*10*10 = 500, or constant time. Works relatively fast. Code is down below. If you want to try some copilot, do it too, but the ones that I tried provided the wrong answer. Cheers, ACC.

Sum of Digit Differences of All Pairs - LeetCode

3153. Sum of Digit Differences of All Pairs
Medium

You are given an array nums consisting of positive integers where all integers have the same number of digits.

The digit difference between two integers is the count of different digits that are in the same position in the two integers.

Return the sum of the digit differences between all pairs of integers in nums.

Example 1:

Input: nums = [13,23,12]

Output: 4

Explanation:
We have the following:
- The digit difference between 13 and 23 is 1.
- The digit difference between 13 and 12 is 1.
- The digit difference between 23 and 12 is 2.
So the total sum of digit differences between all pairs of integers is 1 + 1 + 2 = 4.

Example 2:

Input: nums = [10,10,10,10]

Output: 0

Explanation:
All the integers in the array are the same. So the total sum of digit differences between all pairs of integers will be 0.

Constraints:

  • 2 <= nums.length <= 105
  • 1 <= nums[i] < 109
  • All integers in nums have the same number of digits.
Accepted
13,922
Submissions
33,270

public long SumDigitDifferences(int[] nums)
{
 //Bucketize the count per position
 long[][] positionCount = new long[nums[0].ToString().Length][];
 for (int i = 0; i < positionCount.Length; i++) positionCount[i] = new long[10];
 foreach (int num in nums)
 {
 int position = positionCount.Length - 1;
 int n = num;
 while (position >= 0)
 {
 positionCount[position][n % 10]++;
 position--;
 n /= 10;
 }
 }
 long retVal = 0;
 foreach (long[] pCount in positionCount)
 {
 for (int i = 0; i < 10; i++)
 {
 if (pCount[i] > 0)
 {
 for (int j = i + 1; j < 10; j++)
 {
 if (pCount[j] > 0)
 {
 retVal += (long)pCount[i] * pCount[j];
 }
 }
 }
 } 
 }
 return retVal;
}

Comments

Post a Comment

[フレーム]

Popular posts from this blog

Quasi FSM (Finite State Machine) problem + Vibe

Not really an FSM problem since the state isn't changing, it is just defined by the current input. Simply following the instructions should do it. Using VSCode IDE you can also engage the help of Cline or Copilot for a combo of coding and vibe coding, see below screenshot. Cheers, ACC. Process String with Special Operations I - LeetCode You are given a string  s  consisting of lowercase English letters and the special characters:  * ,  # , and  % . Build a new string  result  by processing  s  according to the following rules from left to right: If the letter is a  lowercase  English letter append it to  result . A  '*'   removes  the last character from  result , if it exists. A  '#'   duplicates  the current  result  and  appends  it to itself. A  '%'   reverses  the current  result . Return the final string  result  after processing all char...

Shortest Bridge – A BFS Story (with a Twist)

Here's another one from the Google 30 Days challenge on LeetCode — 934. Shortest Bridge . The goal? Given a 2D binary grid where two islands (groups of 1s) are separated by water (0s), flip the fewest number of 0s to 1s to connect them. Easy to describe. Sneaky to implement well. 🧭 My Approach My solution follows a two-phase Breadth-First Search (BFS) strategy: Find and mark one island : I start by scanning the grid until I find the first 1 , then use BFS to mark all connected land cells as 2 . I store their positions for later use. Bridge-building BFS : For each cell in the marked island, I run a BFS looking for the second island. Each BFS stops as soon as it hits a cell with value 1 . The minimum distance across all these searches gives the shortest bridge. πŸ” Code Snippet Here's the core logic simplified: public int ShortestBridge(int[][] grid) { // 1. Mark one island as '2' and gather its coordinates List<int> island = FindAndMark...

Classic Dynamic Programming IX

A bit of vibe code together with OpenAI O3. I asked O3 to just generate the sieve due to laziness. Sieve is used to calculate the first M primes (when I was using Miller-Rabin, was giving me TLE). The DP follows from that in a straightforward way: calculate the numbers from i..n-1, then n follows by calculating the min over all M primes. Notice that I made use of Goldbach's Conjecture as a way to optimize the code too. Goldbach's Conjecture estates that any even number greater than 2 is the sum of 2 primes. The conjecture is applied in the highlighted line. Cheers, ACC. PS: the prompt for the sieve was the following, again using Open AI O3 Advanced Reasoning: " give me a sieve to find the first M prime numbers in C#. The code should produce a List<int> with the first M primes " Minimum Number of Primes to Sum to Target - LeetCode You are given two integers  n  and  m . You have to select a multiset of  prime numbers  from the  first   m  pri...