Posts

The power of pruning in backtracking V

Image
Backtracking is a great technique in algorithms, but it needs to be accompanied by aggressive pruning or else it may quickly become intractable. This was an interesting problem, and the small input numbers (10^5 and k<=5) tells me that the authors knew that this could quickly become intractable, even with pruning. The pruning here primarily happens in two occasions: first during the base case (k==0), second when the product becomes larger than n. Comparing my solution with Sonnet 4's and ChatGPT 5's (and I gave them all the hints too), there is a small gain in my solution compared to theirs. It was surprising to see that Anthropic's one didn't make use of pruning as well as mine's or ChatGPT 5's. Code is down below, cheers, ACC. Balanced K-Factor Decomposition - LeetCode Given two integers  n  and  k , split the number  n  into exactly  k  positive integers such that the  product  of these integers is equal to  n . Return  any ...

The power and simplicity of IComparer V

Image
Easy problem but it shows the power of IComparer. There are multiple possible solutions here, hence you let the IComparer do the job by just comparing the absolute values in the (internal) QuickSort implementation. Code is down below, cheers, ACC. Sort Array By Absolute Value - LeetCode You are given an integer array  nums . Rearrange elements of  nums  in  non-decreasing  order of their absolute value. Return  any  rearranged array that satisfies this condition. Note : The absolute value of an integer x is defined as: x  if  x >= 0 -x  if  x < 0   Example 1: Input:   nums = [3,-1,-4,1,5] Output:   [-1,1,3,-4,5] Explanation: The absolute values of elements in  nums  are 3, 1, 4, 1, 5 respectively. Rearranging them in increasing order, we get 1, 1, 3, 4, 5. This corresponds to  [-1, 1, 3, -4, 5] . Another possible rearrangement is  [1, -1, 3, -4, 5]. Example 2: Input:   nums = [-100,100] ...

Sieve of Eratosthenes to solve a Leetcode problem III

Image
In this case the Sieve is applied directly to the main loop. Notice that you don't need to save off the elements in different arrays, only add them up. Also important to note that composite numbers can be created in multiple ways (for example, 2*6 == 3*4), hence keep track of which ones you have seen before to avoid double counting. No GAI involved, except at the very bottom to compute the Big-O time complexity, which I think it would have been of the order of NLogN, but the true analysis from OpenAI O3 (Advanced Reasoning) is down below. So is the code. Cheers, ACC. Split Array by Prime Indices - LeetCode You are given an integer array  nums . Split  nums  into two arrays  A  and  B  using the following rule: Elements at  prime  indices in  nums  must go into array  A . All other elements must go into array  B . Return the  absolute  difference between the sums of the two arrays:  |sum(A) - sum(B)| . Note: ...