{"id":21961893,"url":"https://github.com/lucasnbsb/data-structures-and-algorithms","last_synced_at":"2025-08-29T16:18:55.779Z","repository":{"id":61518570,"uuid":"546220618","full_name":"lucasnbsb/Data-Structures-and-Algorithms","owner":"lucasnbsb","description":"Studying data structures and algorithms, mostly on leetcode","archived":false,"fork":false,"pushed_at":"2023-07-09T12:31:10.000Z","size":289,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-22T20:30:48.294Z","etag":null,"topics":["algorithms","data","structures"],"latest_commit_sha":null,"homepage":"https://leetcode.com/lucasnbsb/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/lucasnbsb.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-10-05T18:29:13.000Z","updated_at":"2023-07-09T17:30:56.000Z","dependencies_parsed_at":"2025-01-28T00:39:17.491Z","dependency_job_id":null,"html_url":"https://github.com/lucasnbsb/Data-Structures-and-Algorithms","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/lucasnbsb/Data-Structures-and-Algorithms","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lucasnbsb%2FData-Structures-and-Algorithms","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lucasnbsb%2FData-Structures-and-Algorithms/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lucasnbsb%2FData-Structures-and-Algorithms/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lucasnbsb%2FData-Structures-and-Algorithms/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/lucasnbsb","download_url":"https://codeload.github.com/lucasnbsb/Data-Structures-and-Algorithms/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lucasnbsb%2FData-Structures-and-Algorithms/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":272717737,"owners_count":24981487,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-08-29T02:00:10.610Z","response_time":87,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["algorithms","data","structures"],"created_at":"2024-11-29T10:19:52.221Z","updated_at":"2025-08-29T16:18:55.730Z","avatar_url":"https://github.com/lucasnbsb.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# A high level description of most solutions i have uploaded so far.\n\n## Motivation:\nI decided to go back and rebuild my skills from the ground up. So i started with Data Structures and Algorithms.\n\n## Accomplishments thus far:\n- was able to pass an Amazon coding challenge to get into the selection process. and the follow up interview\n- Participated in 6 Leetcode contests, rated 1587, top 23% , still climbing\n- Got my 50 days of leetcode badge\n- 200 problems solved.\n\n## What i gained so far:\n- I'm able to read and understand code much faster\n- Gained an understanding of DSA stronger than what i had coming out of college years ago.\n- Learned python\n- Wrote faster code overal ever since\n\n# Hard\n### 23. Merge k Sorted Lists\n    - Divide-and-conquer\n    - make a helper function to merge 2 lists and decrement the running count of lists\n    - treverse the input in pairs mergin the pairs while the count of lists \u003e 1\n    - easier than most mediums.\n\n### 30. Substring with Concatenation of All Words\n    - Sliding window, setup by figuring out the window size (len(word)) and initializing a hashmap with the words and count in the input\n    - traverse the input string jumping by window size\n    - check the substring from the current position to the end of the window size, and update a copy of the counting hashmap to keep track of the remaining words.\n    - if the remaining goes below zero or the number or words remaining is different from the words used continue, else add the current index to the output.\n### 42. Trapping Rain Water.py\n    - get a helper array\n    - traverse normaly registering the max height seen up to the current\n    - traverse backwards updating the helper with min(maxFromRight, maxFromLeft - h) ( the amount of water in any given rectangle\n    - sum the helper\n\n### 51 N-Queens and 52. N-Queens II\n    - this one is actually hard.\n    - backtracking (dfs)\n    - use the len of queens as rows, that takes care of that check\n    - put in the array of queens the column in which the queen should go\n    - if you placed 4 queens append the array to the output\n    - check for the column by checking the array of queens\n    - check for diagonals by checking X-Y = P-Q for the antidiagonal and X+Y = P+Q for the diagonal\n    - if you pass, recursive call adding the column to the rows array and the diff and sum to the arrays of diff and sum\n    - you can also use a set or a hashmap, but the array has less overhead since you are already checking for existance\n\n### 76. Minimum Window Substring\n    - sliding window, expand right until you get a valid window\n    - remove from left until window is invalid\n    - keep walking right and left to the end and testing agains the minimum window\n\n### 239. Sliding Window Maximum\n    - keep a queue of elements\n    - at every new element:\n      - remove from the queue the ones outside the window range\n      - remove the ones smaller than the current\n      - append the current\n      - if you are in window range, append to the output the head of the queue\n\n### 297. Serialize and Deserialize Binary Tree\n    - either BFS or DFS, not that hard tbh, just traverse to serialize and keep an index running\n    - to deserialize\n\n### 295 Find the running medinan (hackerrank and leetcode):\n    - 2 heaps, one min one max, top of each heap should be the middle of the stream\n    - push into one, pop from that one and push into the other.\n    - that reorders the middle\n    - determine which one is always gonna be bigger, test and pushpop accordingly\n    - to get the median check if the designated bigger is bigger, if so peek it\n    - if not they are equal, so peak both and divide by 2\n\n### swap nodes algo (hackerrank)\n    - not that difficult, assemble the tree by using a queue (basicaly bfs)\n    - implement the inorder traversal\n    - do bfs but swapping if the level (1 indexed ) % k == 0.\n    - push the result to the output\n    - make sure that the recursion pile doesnt break.\n\n# Medium\n### 3  Longest Substring Without Repeating Characters\n    - keep a sliding window, right pointer is just the variable of the foor loop\n    - track a set of the seen characters\n    - remove all characters maching the left pointer as it walks along , till you get to the repeated character\n    - update maxsize after before walking the right pointer\n\n### 5. Longest Palindromic Substring\n    - two pointer scan on every position\n    - keep track of the largest string\n    - check for odd and even length strings by having the check start with r and l at the same position (odd) and on consecutive positions (even)\n\n### 7. Reverse Integer\n    - store a boolean for isnegative on the number\n    - use the absolute value of the number\n    - while x \u003e 0: add the modulo to the output, multiply the output by 10\n    - outside the while divide the output by 10, it will always run one more time\n    - with modulo = 0, not affecting the number\n    - put the negative back in if isneg\n    - all math, no string manipulation for that 96 percentile\n\n### 11. Container With Most Water\n    - make a helper method to calculate the area\n    - keep two pointers one at the start and one at the end of the array\n    - check the area of the current pair (start, end)\n    - check which one is bigger and walk the other towards the middle\n    - stop when they cross\n\n### 17. Letter Combinations of a Phone Number\n    - Basic backtracking problem, iterate through the digits\n    - make a recursive call with each of the letters on a stack\n    - when the digits run out ''.join(the stack) into the output\n\n### 19. Remove Nth Node From End of List\n    - Hint says: keep a second pointer n steps behind\n    - my solution whas to traverse and make an array\n    - then treat the 3 cases. remove at start, end and middle\n\n### 28. Find the Index of the First Occurrence in a String\n    - https://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_algorithm\n    - basically use a hash to check the substring.\n    - but also only do the hash if you have the first letter matching since it`s expensive\n    - take good care of the limits in the range\n\n### 30. Substring with Concatenation of All Words\n    - build a method to check whether the window is valid by traversing it\n    and checking it against a copy of the words dictionary\n    - traverse the input string until 1+size(s)-wordlengh checking the\n    validity of the window and appending the index to the result\n\n### 33. Search in Rotated Sorted Array\n    - its still binary search\n    - for every mid you have to figure out in what sorted half you are and then act acordingly\n\n### 36. Valid Sudoku\n    - this one hinges heavily on the data structure you choose\n    - get some defaultdict(set)s going. for rows, collumns and squares\n    - the trick is to address the squares one with a tuple made of x//3, y//3 to check for repetitions within the square\n    - then just itterate, check for repetitions on all 3, return false if repeated, and add to the sets if not.\n\n### 49. Group Anagrams\n    - use a hashmap. key is the word sorted( ''.join(sorted(word))) value is an array of lists.\n    - you can use a defaultdict(list) for that.\n    - iterate over the values and append to output\n### 54. Spiral Matrix.py\n    - two pointers approach, four pointers edition\n    - big loop, check if pointers cross\n    - four small loops for every direction, check again in the middle for pointers crossing\n    - take a lot of care with the indices on right and bottom for they are out of bounds\n\n### 55. Jump Game\n    - start backwards, keep a goalpost on the last element\n    - shift the goalpost (greedy) as you find possible jumps to the goal\n    - return true if goalpost hits the 0 element\n\n### 56. Merge Intervals.py\n    - sort the intervals by starting position\n    - traverse the sorted intervals\n    - check if the last interval ends after the current start, if so merge them in the output\n    - if they dont just append to output\n\n### 62. Unique Paths\n    - two dimentional dp.\n    - figure out what a position needs to calculate\n    - work backwards from the end\n    - realize the last column and last row have all 1's in the how many paths from here to the end department\n    - fill those ones,\n    - iterate inside the remaining matrix calculating the current position by calculating the sum of the right and the down one from there\n    - return the [0][0] position\n    - IF YOU EVEN SUSPECT DP PUT IT IN PAPER. the problem gets much easier once you have visualized it\n\n### 63. Unique Paths II\n    - Basicaly the obstacle sets the value to 0\n    - And you have to pay attention to propagate zeroes on the last column and last row.\n    - Once you solved Unique Paths 1 it's just a small adjustment\n\n### 73. Set Matrix Zeroes\n    - use the first position of the rows and colums to mark for zeroes and sweep around\n    - to actualy do it easier use 2 arrays to index where to blank out\n\n### 128. Longest Consecutive Sequence\n    - hashmap all values\n    - traverse the array again, if the current is not the start of a sequence ( last one is not in the map)\n    - start counting and updating the max\n### 131. Palindrome Partitioning\n    - traverse the input calling dfs, only go deeper if the substring up to the index checked is a palindrome\n    - to go deeper, add the current partition to the path and reduce the input\n### 136. Single Number\n    - just xor everything, make use of the fact that x^x = 0\n### 138. Copy list with random pointer\n    - iterate once creating the copy without the rando\n    - make a reference with a hashmap from the old to the new\n    - traverse the old again linking the random with the adress\n### 143. Reorder List\n    - put the nodes on a hashmap so you can index them like an array\n    - then just iterate pointing the next at the right nodes\n    - take care of the indexing in the hashmap.  \n### 150. Evaluate Reverse Polish Notation\n    - nasty type conversions in the division case\n    - otherwise its polish notation, just stack it up and\n    - mind the order of the operators\n### 153. Find Minimum in Rotated Sorted Array\n    - binary search in rotated, same idea as the other one (ctrl+f for rotated)\n### 167. Two Sum II - Input Array Is Sorted\n    - binary search\n    - walk the right and left pointers one by one\n### 198. House Robber\n    - A pretty fundamental problem in learning DP\n    - Always the same approach, identify the recursive relationship, simplify into what is actualy needed to calculate the next position.\n    - this one is way easier if you visualize the dp cache in terms of robIncludingLast and robExcludingLast\n\n### 213. House Robber II\n    - run house robber 1 on the array ignoring the first and last position and take the max\n    - House robber 1 is dp with the two variables for robIncludingLast and robExcludingLast\n### 211. Design Add and Search Words Data Structure\n    - Use a trie\n    - use a dfs helper function to get the wildcard characters\n    - pretty easy\n### 221. Maximal Square\n    - DP, also it's anoying that the matrix is in chars instead of int\n    - m[i][j] = 1 + min(m[i+1][+1], m[i+1][j], m[i][j+1]).\n    - nothing much else aside from the fundamental relation of the problem and subproblem\n### 236. Lowest Common Ancestor of a Binary Tree\n    - you don`t have to keep going once you find one of the nodes\n    - run dfs, return if you find the node or on null\n    - check if left and right (found both on different branches) and return root\n    - then left or right (found one and the other was downstream) and return the one not null (it is the ancestor itself)\n### 238. Product of Array Except Self\n    - calculate the list of prefix multis and postfix multis for every i.\n    - return pre[i]*pos[i]\n    - the operation can be done inside the output array for O(N) extra memory\n### 253. Meeting rooms 2\n    - get a sorted list of start and end times\n    - iterate on the start list\n    - compare start and end\n    - each start before and end increments\n    - each end decrements\n    - get the max\n#### 287. Find the Duplicate Number\n    - floyds algo. use slow fast to find the cycle. reset one of them to the start\n    - walk both at the same pace till they meet at the start of the loop\n\n### 371. Sum of Two Integers\n    - this is easy on every language but python\n    - carry is an and shifted\n    - sum is a xor. keep iterating\n\n### 347. Top K Frequent Elements\n    - iterate first to create a counter map\n    - iterate the keys and push them into a max heap\n    - pop the heap k times\n### 416. Partition Equal Subset Sum\n    - Knapsack 0/1 for half the value of the sum.\n\n### 516. Longest Palindromic Subsequence\n    - 2D dp. dp[l][r] is the longest palindromic subsequence from l to r\n    - draw it out\n    - if l = r then 1\n    - if the positions match the length is 2 + the length of the inner subsequence\n    - if they are not dp is equal the max of each subsequence reducing from the left or right\n    - iterate backwards through the rows. \n\n### 547. Number of Provinces\n    - Run union find.\n    - after the union, if a union has been performed you can decrement a counter starting at the number of cities\n### 567. Permutation in String\n    - count into a dictionary the letters of s1\n    - slide a window of size (len(s1)-1) on s2 putting into a dictionary and check for equality of values in the dict.\n\n### 621. Task Scheduler\n    - traverse to make a counter\n    - get a maxheap for the counter\n    - get a queue to model the cooldownzone,\n    - the length of the queue is the cooldown\n\n### 647. Palindromic Substrings\n    - run a two pointers scan for every position (l and r at i)\n    - accounting for odd lengths and even lengths (l = i, r = i+1)\n### 739. Daily Temperatures\n    - monotone decreasing stack\n    - start output with all 0s\n    - stack the temps lower than the top\n    - pop the ones larger than the top and update the corresponding index\n### 853. Car Fleet\n    - sort the array by distance\n    - iterate in reverse\n    - use the eta to count the fleets\n### 981. Time Based Key-Value Store\n    - hashmap of lists for the store\n    - binary search for the indexing\n### 994. Rotting Oranges\n    - Matrix BFS\n    - Treverse first to determine where are the first rotten oranges and count the fresh ones\n    - Run bfs from each rotten one and everytime you hit a fresh one update the count and put it in the rotten queue.\n\n### 1091. Shortest Path in Binary Matrix\n    - Run BFS on the matrix.\n    - check for stop condition as you pop from the pile\n    - return -1 on default\n    - pay attention to the conditions,\n    - min(rows,cols) \u003c 0 is a nice way to cut down on too much code.\n    - max(rows,cols) \u003e ROWS or COLS also a nice way if it is always square\n\n### 1147 Longest Common Subsequence\n    - Both bottom up and top down approaches work\n    - with DP the problem is always figuring out how to find the subproblems and visualizing\n    - the relationship of the problem and the subproblem\n    - in this case we use a matrix of len(text1)+1 x len(text2)+1 to serve as the cache\n    - the relationship is that if your indexed characters mach you increment both strings so you move diagonaly\n    - if they dont you get the max of the increment of either, so the right and down ( or up and left, depending on how you are traversing.)\n    - \n\n### 1161. Maximum Level Sum of a Binary Tree (google prep)\n    - Run bfs, make sure to use -inf as the maxSum\n\n### 1448. Count Good Nodes in Binary Tree\n    - DFS\n    - keep a running maximum, compare each node to the maximum\n    - add to the list of good nodes accordingly\n\n### 2491. Divide Players Into Teams of Equal Skill\n    - find the target skill by finding the max and min in the same treversal.\n    - while populating a counting dictionary\n    - walk the min and max closer to the midle in a loop checking if both hit the dict simetrically\n    - decrement the counts on the dict and update the running sum accordingly\n    - return -1 all the way if conditions are not satisfied\n\n### 2527. Find Xor-Beauty of Array\n    - this one is nice. once you put the computation to paper everything cancels out\n    - and you just have to XOR the main diagonal of the matrix\n    - only the cases where i=j=k actually contribute to the output\n\n### 2530. Maximal Score After Applying K Operations\n    - be greedy, put everything into a max heap\n    - pop and push k times applying the opperation\n# Easy\n## 1 Two sum:\n    - make a hashmap [dif:number]\n    - check difference between target and curr\n    - if the diff is in the map thats the 2 numbers\n## 2 Valid parenthesis:\n    - hashmap [closed:open]\n    - if in map (is closed) -\u003e pop from the stack, has to match the top of the stack, otherwise false\n    - if is oppen just append\n## 21 Merge Two Sorted Lists:\n   e - start a dummy pointer\n    - two pointer for each list\n    - while both are good, check and point acordingly\n    - one of the pointers are still good, just point the tail to it\n## 66 Plus One\n    - traverse from smallest position to largest\n    - add and set the carry\n    - at the end check if the carry is 1 to put the new position\n## 69 sqrt(x)\n    - binary search the space between 0 and X\n## 70 Climbing Stairs\n    - DP from 0 to Number of stairs, turns out its fibbonacci\n    - on n-1 how many ways to reach goal, what abount n-2, and n-3.\n## 88 Merge Sorted Arrays\n    - traverse reversed so you dont have to shift\n    - walk along with m and n -\u003e nums[m+n-1] is the first 0 from the back\n    - num1 may be left at the end.\n## 94 Binart Tree Inorder Traversal\n    -left, node, right.\n## 104 Maximum Depth of Binary Tree:\n    - its dfs, but in a preorder fashion you test\n    - for the max height and if its a leaf node\n## 112 Path Sum\n    - dfs with a stack\n    - push,test if sum is path and leaf, left, right, pop\n## 145 Binart tree Postorder\n    - left, right, node\n\n## 191. Number of 1 Bits\n    - hamming weight algo\n    - just shift and count with \u0026 1\n## 206 Reverse Linked List\n    - keep a pointer to the last\n    - use a temporary next pointr\n    - point to last and walk last, then walk head\n## 217 Contains Duplciate\n    - just use a hashmap\n## 219 Contains Duplicate 2\n    - hashmap, and if its there, check the abs\n## 278 First Bad Version\n    - Thats a generic binary search, Remember the algo\n    - gotta have a function to test.\n\n## 338. Counting Bits\n    - sum the \u00261 and shift\n\n## 344 Reverse String\n    - Two pointers start and end, start \u003c end, swap and walk\n## 350 Intersection of Two Arrays\n    - count the occurences with a hashmap\n    - traverse the second and decrement the occurences in the map\n## 374 Guess Number Higher Lower\n    - Generic Binary search with higher lower\n## 509 Fibonacci Number\n    - 0 and 1 hardcoded\n    - m = fib(n-1) fib(n-2), go recursive\n## 682 Baseball Game\n    - Its just stack operations in an array\n## 700 Search in a binary search Tree:\n    - if \u003e self.search(right)\n    - if \u003c self.search(left)\n    - else return \n## 704 Binary Search\n    - Thats all that it is\n## 724 Pivot Index\n    - Calculate an array of sums up to the position\n    - traverse and check if 2*sum[i] == sum[-1] + nums[-1] (total sum)\n## 905 Sort Array By Parity\n    - using 2 extra arrays, separate and concatenate\n## 976 Largest Perimeter Triangle\n    - traverse back to front the miolo of the array running the test\n## 1700 Number of Students unable to Eat\n    - track the number of refusals.\n    - if everybody or nobody refuses get out\n    - use a stack to model the behavior\n## 1929 Concatenation of Array\n    - just concatenate lol\n## 2164 Sort Even and Odd Indempentently\n    - append odds and evens to their helper arrays\n    - bucket sort them out\n    - merge\n## 2373 Largest Local in the Matrix\n    - its just a matter of treversing the right way\n    - you have to check all of them.\n\n### 2529. Maximum Count of Positive Integer and Negative Integer\n    - the title is the answer, this took 40 seconds","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flucasnbsb%2Fdata-structures-and-algorithms","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flucasnbsb%2Fdata-structures-and-algorithms","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flucasnbsb%2Fdata-structures-and-algorithms/lists"}