Posts

Showing posts from September, 2024

N^2 with Pruning

Image
N^2 solutions sometimes can be pruned to a point that they actually work well. This is an example: we can solve in N^2 by going thru all the substrings, but if we get to a point where the count of consonants is less than zero, we skip the inner loop, cutting down the search time considerably. Code is down below, cheers, ACC. Count of Substrings Containing Every Vowel and K Consonants I - LeetCode 3305. Count of Substrings Containing Every Vowel and K Consonants I Medium 34 4 Add to List Share You are given a string  word  and a  non-negative  integer  k . Return the total number of  substrings  of  word  that contain every vowel ( 'a' ,  'e' ,  'i' ,  'o' , and  'u' )  at least  once and  exactly   k  consonants.   Example 1: Input:   word = "aeioqq", k = 1 Output:   0 Explanation: There is no substring with every vowel. Example 2: Input:   word = "aeiou", k = 0 Output:   1 Explanation: The only substring with every vowel and

Grid - Breadth First Search (BFS) - IV

Image
Requires a standard BFS to solve it. The only caveat is that you may reach a cell that has been reached before but if you reach it with more health than before, it is OK to proceed. Code is down below, cheers, ACC. Find a Safe Walk Through a Grid - LeetCode 3286. Find a Safe Walk Through a Grid Medium 62 7 Add to List Share You are given an  m x n  binary matrix  grid  and an integer  health . You start on the upper-left corner  (0, 0)  and would like to get to the lower-right corner  (m - 1, n - 1) . You can move up, down, left, or right from one cell to another adjacent cell as long as your health  remains   positive . Cells  (i, j)  with  grid[i][j] = 1  are considered  unsafe  and reduce your health by 1. Return  true  if you can reach the final cell with a health value of 1 or more, and  false  otherwise.   Example 1: Input:   grid = [[0,1,0,0,0],[0,1,0,1,0],[0,0,0,1,0]], health = 1 Output:   true Explanation: The final cell can be reached safely by walking along the gray cells be