Posts

Showing posts from September, 2023

Remoteness in Linear Time

Image
Approach here could be using either a queue or stack, but basically for each cell, traverse the connected nodes, calculate the sum of the connected notes. To avoid a second pass, use a proxy hash table. At the same time calculate the total sum of the grid. Do another linear pass at the end to calculate the remoteness since you have all the data that you need pre-calculated and stored in the hash tables. Code is down below, cheers, ACC. Sum of Remoteness of All Cells - LeetCode 2852. Sum of Remoteness of All Cells Medium 9 0 Add to List Share You are given a  0-indexed  matrix  grid  of order  n * n . Each cell in this matrix has a value  grid[i][j] , which is either a  positive  integer or  -1  representing a blocked cell. You can move from a non-blocked cell to any non-blocked cell that shares an edge. For any cell  (i, j) , we represent its  remoteness  as  R[i][j]  which is defined as the following: If th...

Geometric Algorithms III

Image
I tried this problem before but was actually over-complicating it a lot. Problem is simpler than I originally thought. Simply use the standard equation for a line, y=ax+b. Find (a,b) given the two first points. Then for every other point, check whether (y_point - a*x_point - b) is zero. That check needs to be a statistical one since we're dealing with floating points. Also take care of the special case where the line is of the form x=constant. Code is down below, cheers, ACC. Check If It Is a Straight Line - LeetCode 1232. Check If It Is a Straight Line Easy 2476 263 Add to List Share You are given an array  coordinates ,  coordinates[i] = [x, y] , where  [x, y]  represents the coordinate of a point. Check if these points make a straight line in the XY plane.     Example 1: Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]] Output: true Example 2: Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]] Output: false   Constrain...

Sliding Window Technique - Part 9

Image
This is the standard implementation of the sliding window technique. In this case the loop variable "i" controls the window, whether it is larger than k or not. Notice that I'm checking for i>=k-1 so account for the very first window, that's why we also need to check whether i-k>=0 before  doing the calculation to decrement/remove the first element of the window. Code is down below, cheers, ACC. Maximum Sum of Almost Unique Subarray - LeetCode 2841. Maximum Sum of Almost Unique Subarray Medium 66 95 Add to List Share You are given an integer array  nums  and two positive integers  m  and  k . Return  the  maximum sum  out of all  almost unique  subarrays of length  k  of   nums . If no such subarray exists, return  0 . A subarray of  nums  is  almost unique  if it contains at least  m  distinct elements. A subarray is a contiguous  non-empty  sequence of elements...