Posts

Showing posts from January, 2024

Ideas from Selection Sort

Image
Selection Sort is a common N^2 sorting technique with the following based premise: find the minimum element of an array (O(N)), move it to be the first. Repeat this for the remaining elements (O(N), hence the total is N^2). In this problem we can use the exact same idea, the only variation is that you need to pre-compute the number-to-countBits for every number, and ensure that the path to move the element to becoming the first adheres to the problem statement (along the way all the numbers need to have the same number of Bits, which you can then make use of the pre-computed map). Code is down below, cheers, ACC. Find if Array Can Be Sorted - LeetCode 3011. Find if Array Can Be Sorted Medium 69 8 Add to List Share You are given a  0-indexed  array of  positive  integers  nums . In one  operation , you can swap any two  adjacent  elements if they have the  same  number of  set bits . You are allowed to do this operation  any  number of times ( including zero ). Return  true   if you can

Very interesting Tree problem II

Image
Another interesting Tree problem, this time more of a design problem: design and implement a locking tree structure. I used hashtable to represent the tree, another hashtable to represent the locked elements, and a copy of the parents array. The upgrade method is O(N), and since it may get called N times, the total complexity is N^2 where N=2x10^3 (reasonable). Full implementation down below, cheers, ACC. Operations on Tree - LeetCode You are given a tree with  n  nodes numbered from  0  to  n - 1  in the form of a parent array  parent  where  parent[i]  is the parent of the  i th  node. The root of the tree is node  0 , so  parent[0] = -1  since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade nodes in the tree. The data structure should support the following functions: Lock:   Locks  the given node for the given user and prevents other users from locking the same node. You may only lock a node using this function if the node is unlo