Posts

Standard Priority Queue VIII: Two Queues

Image
This is an interesting problem where you do need a priority queue in order to simulate the game (remember to use Max-Color as the priority since the dequeuing is based on smaller priorities first), but the tricky part here is that you cannot enqueue in the main loop while each round simulation is going on otherwise you'll starve lower priority colors. Hence in the middle of the main simulation loop, instead of enqueuing, just save off the elements to be enqueued later. I used another pQueue for this reason, but you could have used a different data structure, pQueues are not necessary here. Code is down below, cheers, ACC. Multi Source Flood Fill - LeetCode You are given two integers  n  and  m  representing the number of rows and columns of a grid, respectively. You are also given a 2D integer array  sources , where  sources[i] = [r i , c i , color ​​​​​​​i ]  indicates that the cell  (r i , c i )  is initially colored with  color i . Al...

Flatten Binary Tree to Linked List II

Image
Another problem where you either have to flatten the binary tree into a linked list, or push it into a queue. I decided to do the former - it is easy to have a list of list of nodes, where each index is the level of the tree, and each list is the list of nodes in that level. If you do a pre-order depth-first search (DFS) you can accomplish that. Second part of the problem is the calculation based on the given rules. Just go thru the flatten list, and to the list of nodes, and process based on the rules. If you look at the code down below, it achieves a high degree of symmetry which is usually a trademark when operating with trees. Cheers, ACC. Zigzag Level Sum of Binary Tree - LeetCode You are given the  root  of a  binary tree . Traverse the tree level by level using a zigzag pattern: At  odd -numbered levels (1-indexed), traverse nodes from  left to right . At  even -numbered levels, traverse nodes from  right to left . While traversing a level in th...