Posts

The Sieve (but not Eratosthenes')

Sieves are a technique in algorithms that lets you build a certain pattern from the ground up in NLogN. The most famous one is the Sieve of Eratosthenes, which lets you compute the prime (or actually the !primes) in NLogN. But you can use Sieves for other problems unrelated to primes. The one below is a good example. The NLogN comes simply from the inner loop condition which goes only to maxVal but it grows very fast, hence this condition here is the key to achieving the LogN (the N comes from the outer loop). Code is down below, cheers, ACC. Minimize Array Sum Using Divisible Replacements - LeetCode You are given an integer array nums . You can perform the following operation any number of times: Choose two indices a and b such that nums[a] % nums[b] == 0 . Replace nums[a] with nums[b] . Return the minimum possible sum of the array after performing any number of operations.   Example 1: Input: nums = [3,6,2] Output: 7 Explanation: Choose a = 1 , b = 2 , where nums[a] = 6 an...

Simulation: Build Generations

This was a very interesting problem in my opinion. It is a classic exercise in simulation, especially related to population growth. The constraints are small enough that you can brute-force and you'll be fine. Some techniques worth mentioning: 1/ Use a hash set for quick verification whether a point is in the generation 2/ Hash using the boundaries - using 7 as a seed works, hence x*7*7 + y*7 + z is a solid hash without the worry of overflowing 3/ Use two lists for generations: current and next 4/ Build next generation using an N^2 approach (it is OK since N = 6) 5/ Prune using the fact that the points in the next generation always have smaller numbers (due to the floor((a+b)/2)), hence if ever any of the indexes of your target is larger than the largest corresponding index in the current generation, you can safely assume that there won't be a solution. Also, prune using the fact that if the next generation isn't larger than the previous one, no solution will be found Code ...