Skip to content

Latest commit

 

History

History
1214 lines (1089 loc) · 64.5 KB

leetcode.md

File metadata and controls

1214 lines (1089 loc) · 64.5 KB
layout title
table
leetcode

leetcode

Below we will go over some leetcode problems that will help with coding specifically for SRE/DevOps/Platform Engineers. We will be using python3 for all the solutions on this page. If your coding skills are not the best please just start with all the easy problems then move onto medium once you get enough confidence.

Problems (75)

Scripting and Automation (11)

Easy (7)

Click for problems
  1. Length of Last Word - Problem #58
  2. Summary This problem involves manipulating strings, which is a common task in scripting. You need to find the length of the last word in a string.
    Solution
    class Solution:
        def lengthOfLastWord(self, s: str) -> int:
            word_list = s.split()
            last_word = word_list[-1]
            lw_count = len(last_word)
            return(lw_count)
    

    Explanation:

    • First we split the words by using split. This will remove all of the spaces if there are any in s
    • We then grab the last word by indexing the last word word_list[-1]
    • We then get the count of the last word by using len and return the count of it. This is just a simple solution to the problem. We can actually trim the answer if needed to the following:
      class Solution:
        def lengthOfLastWord(self, s: str) -> int:
            s = s.rstrip()  #or strip
            return len(s.split()[-1])
      
  3. Add Binary - Problem #67
  4. Summary This problem simulates binary addition. In scripting, you might encounter scenarios where you need to perform calculations on binary data.
    Solution
    class Solution:
        def addBinary(self, a: str, b: str) -> str:
    

    Explanation:

    • We use int to convert the string to an integer and use base 2
    • We use format to convert the integer back into binary without the "0b" Another way that we can solve this is by using bin Similarly we just remove the first 2 strings.
    class Solution:
        def addBinary(self, a: str, b: str) -> str:
            return bin(int(a , 2) + int(b,2))[2:]
    
  5. Pascal's Triangle II - Problem #119
  6. Summary This problem deals with generating rows of Pascal's Triangle, which can be used in various automated data generation scenarios.
    Solution
    class Solution:
        def getRow(self, rowIndex: int) -> List[int]:
            result = []
            for i in range(0, rowIndex+1):
                result.append([])
    
            <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">0</span>, i + <span class="hljs-number">1</span>):
                <span class="hljs-keyword">if</span> x == <span class="hljs-number">0</span>:
                    <span class="hljs-literal">result</span>[i].append(<span class="hljs-number">1</span>)
                <span class="hljs-keyword">elif</span> i == x:
                    <span class="hljs-literal">result</span>[i].append(<span class="hljs-number">1</span>)
                <span class="hljs-keyword">else</span>:
                    <span class="hljs-literal">result</span>[i].append((<span class="hljs-literal">result</span>[i-<span class="hljs-number">1</span>][x-<span class="hljs-number">1</span>]) + (<span class="hljs-literal">result</span>[i-<span class="hljs-number">1</span>][x]))
        <span class="hljs-keyword">return</span> <span class="hljs-literal">result</span>[rowIndex]
    

    Explanation: This problem asks you to return the rowIndex-th (0-based index) row of Pascal's Triangle as a list of integers. Pascal's Triangle is a triangular array of binomial coefficients, where each number is the sum of the two numbers directly above it. The first few rows of Pascal's Triangle look like this:

    Row 0: [1]
    Row 1: [1, 1]
    Row 2: [1, 2, 1]
    Row 3: [1, 3, 3, 1]
    
    1. We create an empty list called result to store the rows of Pascal's Triangle. Create an empty list called result to store the rows of Pascal's Triangle.

    2. We then iterate over the rows from 0 to rowIndex, inclusive, using the variable i to represent the current row index.

    3. For each row, append an empty list to the result list. This empty list will be used to store the elements of the current row.

    4. Inside the inner loop, iterate over the elements in the current row from 0 to i, using the variable x to represent the current column index.

    5. For each element, check if it is the first element in the row (i.e., x == 0) or the last element in the row (i.e., i == x). If it is either the first or last element, append a 1 to the current row because the first and last elements of each row in Pascal's Triangle are always 1.

    6. If the element is not the first or last element, calculate its value by adding the element from the previous row in the same column (result[i-1][x-1]) and the element from the previous row in the next column (result[i-1][x]). This follows the rule of Pascal's Triangle where each element is the sum of the two elements above it.

    7. Append the calculated value to the current row.

    8. Repeat steps 5-7 for all elements in the current row.

    9. Once the inner loop finishes, the current row is complete, and you move on to the next row.

    10. Finally, return the row at the rowIndex index from the result list.

  7. Merge Sorted Array - Problem #88
  8. Summary This problem is about merging arrays, a common task in scripting when you're working with data from various sources.
    Solution
            class Solution:
        def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
            while m > 0 and n > 0:
                if nums1[m-1] > nums2[n-1]:
                    nums1[m+n-1] = nums1[m-1]
                    m -= 1
                else:
                    nums1[m+n-1] = nums2[n-1]
                    n -= 1
            for i in range(n):
                nums1[i] = nums2[i]
    

    Explanation: To go through this solution, we will go through line by line.

    1. starting with the while loop. It will continue as long as both m and n are greater than 0. This will help merge the two arrays.

    2. Inside the loop, we then compare the last element of nums1 at a index of m-1 with the last element of nums2 at index n-1. These are the largest elements of each array.

    3. If the element in nums1 is greater, it means that this element should be placed at the end of the merged array, which is at index m+n-1 in nums1. So, it assigns the value of nums1[m-1] to nums1[m+n-1]. This merges the element from nums1 into the array.

    4. After merging an element from nums1 it decreases m by 1 to move the m pointer to the previous element in nums1

    5. If the element in nums2 is greater or equal to nums1 then that means that this element should be placed at the end of the merged array.

    6. From the line aboves if statement , we then assign the value of nums2[n-1] to nums1[m+n-1] to merge the elements from nums2 to nums1

    7. After merging an element from nums2 it decrements n by 1 to move the n pointer to the previous element in nums2 n -= 1

    8. After the while loop exits, there might be remaining elements in nums2 that were not merged. This for loop iterates over the remaining elements of nums2 from index 0 to n-1 for i in range(n)

    9. In the for loop, it copies the remaining elements from nums2 into nums1 by merging the remaining elements from nums2 to into nums1 nums1[i] = nums2[i]

    The key idea here is to work from the end of the arrays towards the beginning, which avoids overwriting elements in nums1 before they are compared and merged. This approach ensures that the merged array is sorted without the need for extra space or creating a new array.

  9. Excel Sheet Column Title - Problem #168
  10. Summary In this problem, you convert a column number into the corresponding Excel column title. Such conversions are often encountered in automated data processing.
    Solution
            class Solution:
        def convertToTitle(self, columnNumber: int) -> str:
            alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
            result=""
            while columnNumber:
                columnNumber=columnNumber-1
                result=alphabet[columnNumber%26]+result
                columnNumber=columnNumber//26
            return result
    

    Explanation: This problem asks you to convert a positive integer, columnNumber, into an Excel sheet column title. Excel column titles are represented using uppercase English letters, and they follow a pattern similar to base 26 numbering, where the digits are represented by the English alphabet (A=1, B=2, ..., Z=26), and when the column number exceeds 26, it starts using two-letter combinations (AA=27, AB=28, ..., ZZ=702, AAA=703, and so on).

    1. We first define alphabet that contains all uppercase letters from A-Z. These strings will be used to map column numbers to titles.

    2. We then initializes an empty string result to store the Excel column title

    3. We start a while loop that continues as long as columnNumber is not zero. The loop will gradually convert the column number to column title.

    4. Inside of the loop, it subtracts 1 from the columnNumber. This is done to handle the fact that the Excel column numbering starts from 1, but our algorithm will work with 0-based indexing.

    5. result = alphabet[columnNumber % 26] + result

    This calculates the remainder when columnNumber is divided by 26. The remainder corresponds to a letter in the alphabet. It then takes that letter at the position in the alphabet string and appends it to the beginning of the result string. This builds the Excel column title from right to left.

    1. columnNumber = columnNumber // 26

    It updates columnNumber by performing an integer division by 26 (columnNumber // 26). This reduces columnNumber to the next lower place value.

    The loop will continue with the reduced columnNumber and the next letter is added to the result string.

    This process continues until columnNumber becomes zero, at which point we have constructed the complete Excel column title in the result string.

    1. We finally return the result string which contains the Excel column title corresponding to the input columnNumber.

    This algorithm effectively converts a decimal number into a base 26 representation using the English alphabet letters and builds the Excel column title accordingly.

  11. Excel Sheet Column Number - Problem #171
  12. Summary
    Solution
  13. Single Number - Problem #136
  14. Summary This problem involves finding a single number in an array where all other numbers appear twice. It's a common task in automated data analysis.
    Solution

Medium (4)

Click for problems
  1. Count and Say - Problem #38
  2. Summary This problem involves generating sequences based on previous values, which can be useful for generating automated sequences of data.
    Solution
  3. Reverse Words in a String - Problem #151
  4. Summary Similar to the previous problem, this asks you to reverse the words in a string but not in-place. Scripting can help automate this process.
    Solution
  5. Basic Calculator II - Problem #227
  6. Summary In this problem, you're asked to reverse the order of words in a string, which can be useful for automating text transformations.
    Solution
  7. Group Anagrams - Problem #49
  8. Summary Automating the process of grouping anagrams from a given list of words is applicable to this problem, aligning with scripting and automation concepts.
    Solution

Networking (13)

Easy (7)

Click for problems
  1. First Unique Character in a String - Problem #387
  2. Summary Relates to processing strings, which is fundamental in networking protocols for parsing and validation.
    Solution
    class Solution:
        def strStr(self, haystack: str, needle: str) -> int:
            while needle in haystack:
                res = haystack.index(needle)
                return res
            else:
                return -1
    

    Explanation

  3. Implement strStr() - Problem #28
  4. Summary In networking, substring matching is used in various applications, from pattern matching to searching for headers in network packets.
    Solution
            class Solution:
        def strStr(self, haystack: str, needle: str) -> int:
            while needle in haystack:
                res = haystack.index(needle)
                return res
            else:
                return -1
    

    Explanation

  5. Valid Anagram - Problem #242
  6. Summary String manipulation, such as character sorting, is used in various networking applications, such as checksum calculations.
    Solution
    class Solution:
        def isAnagram(self, s: str, t: str) -> bool:
            if sorted(s) == sorted(t):
                return True
            else:
                return False
    

    Explanation

  7. Isomorphic Strings - Problem #205
  8. Summary Understanding character mappings is important in networking tasks like encoding and decoding.
    Solution
    class Solution:
        def isIsomorphic(self, s: str, t: str) -> bool:
            if len(s) != len(t):
                return False
            else:
                d1, d2 = {}, {}
                for i in range(len(s)):
                    str1, str2 = s[i], t[i]
                    if str1 not in d1:
                        d1[str1] = str2
                    if str2 not in d2:
                        d2[str2] = str1
                    if d1[str1] != str2 or d2[str2] != str1:
                        return False
            return True
    

    Explanation

  9. Pascal's Triangle - Problem #118
  10. Summary While not a direct analogy, data organization and computation are crucial in networking protocols and data transmission.
    Solution
            class Solution:
        def generate(self, numRows: int) -> List[List[int]]:
            result = []
            for i in range(0, numRows):
                result.append([])
    
            <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">0</span>, i + <span class="hljs-number">1</span>):
                <span class="hljs-keyword">if</span> x == <span class="hljs-number">0</span>:
                    <span class="hljs-literal">result</span>[i].append(<span class="hljs-number">1</span>)
                <span class="hljs-keyword">elif</span> i == x:
                    <span class="hljs-literal">result</span>[i].append(<span class="hljs-number">1</span>)
                <span class="hljs-keyword">else</span>:
                    <span class="hljs-literal">result</span>[i].append((<span class="hljs-literal">result</span>[i-<span class="hljs-number">1</span>][x-<span class="hljs-number">1</span>]) + (<span class="hljs-literal">result</span>[i-<span class="hljs-number">1</span>][x]))
        <span class="hljs-keyword">return</span> <span class="hljs-literal">result</span>
    

    Explanation

  11. Move Zeroes - Problem #283
  12. Summary In networking, data reorganization may be necessary for efficient data transmission.
    Solution
            class Solution:
        def moveZeroes(self, nums: List[int]) -> None:
            """
            Do not return anything, modify nums in-place instead.
            """
            for i in nums:
                if i == 0:
                    nums.remove(i)
                    nums.append(0)
    

    Explanation

  13. Reverse Vowels of a String - Problem #345
  14. Summary String manipulation and transformation are important in many text-based networking applications.
    Solution
            def reverseVowels(self, s: str) -> str:
        vowels = re.findall('[aeiouAEIOU]', s)
        return re.sub('[aeiouAEIOU]', lambda _ : vowels.pop(), s)
    

    Explanation

Medium (6)

Click for problems
  1. 3Sum - Problem #15
  2. Summary In networking, searching for patterns or matches within data streams is a common task.
    Solution
  3. Longest Palindromic Substring - Problem #5
  4. Summary String processing is essential in networking, such as when parsing and validating URLs or extracting specific data.
    Solution
  5. ZigZag Conversion - Problem #6
  6. Summary Resembles data reformatting tasks seen in networking, such as transforming data for compatibility.
    Solution
  7. Rotate Image - Problem #48
  8. Summary Transforming data, as in rotating an image, is analogous to data transformation in networking tasks.
    Solution
  9. Longest Consecutive Sequence - Problem #128
  10. Summary
    Solution
  11. Find Peak Element - Problem #162
  12. Summary Relates to analyzing sequences of data, important in networking for detecting patterns and trends.
    Solution

Performance Optimization (7)

Easy (2)

Click for problems
  1. Best Time to Buy and Sell Stock - Problem #121
  2. Summary
    Solution
            class Solution:
        def maxProfit(self, prices: List[int]) -> int:
            if not prices:
                return 0
    
        <span class="hljs-keyword">max</span>Profit = <span class="hljs-number">0</span>
        <span class="hljs-keyword">min</span>Purchase = prices[<span class="hljs-number">0</span>]
        <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">1</span>, len(prices)):        
            <span class="hljs-keyword">max</span>Profit = <span class="hljs-keyword">max</span>(<span class="hljs-keyword">max</span>Profit, prices[i] - <span class="hljs-keyword">min</span>Purchase)
            <span class="hljs-keyword">min</span>Purchase = <span class="hljs-keyword">min</span>(<span class="hljs-keyword">min</span>Purchase, prices[i])
        return <span class="hljs-keyword">max</span>Profit
    

    Explanation

  3. Merge Two Sorted Lists - Problem #21
  4. Summary
    Solution
            class Solution:
        def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
    
        merged = ListNode() <span class="hljs-comment"># Create an empty ListNode to serve as the dummy node for the merged list.</span>
        current = merged <span class="hljs-comment"># Initialize a pointer 'current' to the dummy node.</span>
        <span class="hljs-comment"># The while loop iterates as long as there are elements in both list1 and list2. Inside the loop, we compare the values of the current nodes in both lists</span>
        <span class="hljs-keyword">while</span> list1 <span class="hljs-keyword">and</span> <span class="hljs-symbol">list2:</span> 
            <span class="hljs-keyword">if</span> list1.val &lt;= list2.<span class="hljs-symbol">val:</span>  <span class="hljs-comment"># Append the smaller value from list1.</span>
                current.<span class="hljs-keyword">next</span> = list1  <span class="hljs-comment"># Move the pointer in list1 to the next node.</span>
                list1 = list1.<span class="hljs-keyword">next</span> <span class="hljs-comment"># Move the pointer in list1 to the next node.</span>
            <span class="hljs-symbol">else:</span>
                current.<span class="hljs-keyword">next</span> = list2 <span class="hljs-comment"># # Append the smaller value from list2.</span>
                list2 = list2.<span class="hljs-keyword">next</span> <span class="hljs-comment"># Move the pointer in list2 to the next node.</span>
            current = current.<span class="hljs-keyword">next</span>  <span class="hljs-comment"># Move the 'current' pointer to the newly appended node.</span>
        <span class="hljs-comment"># Append any remaining elements from list1 or list2</span>
        <span class="hljs-keyword">if</span> <span class="hljs-symbol">list1:</span>
            current.<span class="hljs-keyword">next</span> = list1 
        elif <span class="hljs-symbol">list2:</span>
            current.<span class="hljs-keyword">next</span> = list2
        <span class="hljs-keyword">return</span> merged.<span class="hljs-keyword">next</span>  <span class="hljs-comment"># Return the merged list starting from the first node.</span>
    

    Explanation merged = ListNode(): We create an empty ListNode named merged to serve as the dummy node for the merged list. This dummy node helps simplify the merging process by providing a starting point for the merged list.

    current = merged: We initialize a pointer current to the dummy node merged. This pointer will be used to traverse and build the merged list.

    The while loop iterates as long as there are elements in both list1 and list2. Inside the loop, we compare the values of the current nodes in both lists and append the node with the smaller value to the merged list.

    current.next = list1 or current.next = list2: We update the next attribute of the current node to point to the smaller node between list1 and list2. This effectively appends the smaller node to the merged list.

    list1 = list1.next or list2 = list2.next: We move the pointer in the corresponding input list (list1 or list2) to the next node, as we've already appended the current node to the merged list.

    current = current.next: We move the current pointer to the newly appended node in the merged list so that the next iteration appends the next smallest node.

    After the loop completes, we check if there are any remaining elements in list1 or list2 and append them to the merged list if necessary.

    Finally, we return the merged list starting from the node after the dummy node (merged.next) to exclude the dummy node from the final result.

Medium (5)

Click for problems
  1. Maximum Subarray - Problem #53
  2. Summary
    Solution
  3. Longest Substring Without Repeating Characters - Problem #3
  4. Summary Optimizing substring calculations, similar to optimizing data processing tasks.
    Solution
  5. Container With Most Water - Problem #11
  6. Summary Optimization of container volume calculations, similar to optimizing data allocation in a system.
    Solution
  7. Search in Rotated Sorted Array - Problem #33
  8. Summary Optimization of search algorithms, crucial in optimizing data retrieval processes.
    Solution
  9. Word Search - Problem #79
  10. Summary Optimization of pattern searching tasks, which is similar to optimizing data processing for finding specific patterns.
    Solution

Troubleshooting and Debugging (8)

Easy (4)

Click for problems
  1. Two Sum - Problem #1
  2. Summary This problem requires problem-solving and debugging skills, similar to identifying issues and bugs in distributed systems.
    Solution
            class Solution:
        def twoSum(self, nums: List[int], target: int) -> List[int]:
            res=[]
            for i in range(len(nums)):
                for a in range(i+1,len(nums)):
                    if (nums[i]+nums[a]==target):
                        res.append(i)
                        res.append(a)
                        break     
            return res
    

    Explanation

  3. Palindrome Number - Problem #9
  4. Summary Involves checking for palindromes, akin to debugging and validating data correctness.
    Solution
            class Solution:
        def isPalindrome(self, x: int) -> bool:
            a = ''.join(reversed(str(x)))
            if a == str(x):
                return True
            else:
                return False
    

    Explanation

  5. Longest Common Prefix - Problem #14
  6. Summary Similar to identifying common patterns, a crucial skill in debugging distributed systems.
    Solution
            class Solution:
        def isPalindrome(self, x: int) -> bool:
            a = ''.join(reversed(str(x)))
            if a == str(x):
                return True
            else:
                return False
    

    Explanation

  7. Valid Parentheses - Problem #20
  8. Summary Debugging skills are important in verifying the correctness of algorithms, a key aspect of troubleshooting.
    Solution
            class Solution:
        def isValid(self, s: str) -> bool:
            while '()' in s or '[]'in s or '{}' in s:
                s = s.replace('()','').replace('[]','').replace('{}','')
            if len(s) !=0:
                return False
            else:
                return True
    

    Explanation

Medium (4)

Click for problems
  1. Compare Version Numbers - Problem #165
  2. Summary Debugging and problem-solving for version comparison, similar to identifying compatibility issues in distributed systems.
    Solution
  3. Decode String - Problem #394
  4. Summary Debugging and problem-solving for decoding tasks, similar to fixing issues with data transformations.
    Solution
  5. Top K Frequent Words - Problem #692
  6. Summary Debugging and problem-solving related to frequent item calculations, similar to identifying and fixing issues with data analysis.
    Solution
  7. Multiply Strings - Problem #43
  8. Summary Debugging and optimizing string multiplication algorithms, crucial in identifying and fixing performance bottlenecks
    Solution

Database Design and Querying (14)

Easy (6)

Click for problems
  1. Combine Two Tables - Problem #175
  2. Summary This problem involves using SQL JOIN to combine information from two different tables based on a common key.
    Solution
  3. Rising Temperature - Problem #197
  4. Summary This problem focuses on querying a Weather table to find days where the temperature was higher than the previous day.
    Solution
  5. Big Countries - Problem #595
  6. Summary This problem involves selecting countries with a population greater than 250 million or an area greater than 3 million square kilometers using SQL.
    Solution
  7. Employees Earning More Than Their Managers - Problem #181
  8. Summary In this problem, you need to compare salaries between employees and their managers using SQL queries.
    Solution
  9. Customers Who Never Order - Problem #183
  10. Summary This problem requires identifying customers who have never placed an order by using a combination of SQL JOIN and NOT EXISTS.
    Solution
  11. Duplicate Emails - Problem #182
  12. Summary The task here is to find duplicate email addresses from a Person table using SQL queries.
    Solution

Medium (8)

Click for problems
  1. Nth Highest Salary - Problem #177
  2. Summary This problem involves finding the Nth highest salary using SQL.
    Solution
  3. Consecutive Numbers - Problem #180
  4. Summary The task is to find numbers that appear at least three times consecutively in a table using SQL queries.
    Solution
  5. Exchange Seats - Problem #626
  6. Summary This problem involves simulating a classroom seating arrangement and exchanging the seats of adjacent students. You are given a table that represents the current seating arrangement with student IDs and their corresponding seats. The task is to design a query that exchanges the seats of adjacent students, assuming that the total number of students is even.

    This problem demonstrates the use of SQL queries to manipulate and update data in a database table. The problem tests your ability to work with relational data, update specific rows, and perform conditional updates based on the positions of students.

    In a real-world scenario, this problem reflects how database queries can be used to manage seating arrangements, perform data updates, and ensure data consistency. It showcases your skills in writing efficient and effective SQL queries to perform specific tasks within a database environment.

    Solution
  7. Product Price at a Given Date - Problem #1164
  8. Summary This problem involves querying a database to find the price of a product at a given date. It requires crafting SQL queries to filter products based on their price history and the provided date. The problem tests your ability to retrieve historical data from a database and filter it based on specific conditions.
    Solution
  9. Second Highest Salary - Problem #176
  10. Summary
    Solution
  11. Last Person to Fit in the Bus - Problem #1204
  12. Summary This problem is about simulating elevator trips for a building. You need to design a query to determine who was the last person to fit in the elevator after a certain time. It involves joining tables, filtering data based on specific conditions, and finding the maximum value. The problem mirrors real-world scenarios where database queries are used to manage and analyze data about people and events.
    Solution
  13. Tree Node - Problem #608
  14. Summary This problem involves working with a database table representing a tree structure. You need to design a query to retrieve information about parent and child relationships within the tree. It's an example of how databases can be used to model hierarchical structures and retrieve data based on those relationships.
    Solution
  15. Rank Scores - Problem #178
  16. Summary In this problem, you are tasked with ranking scores in a database table. You need to design a query that assigns ranks to scores while handling cases of ties. This problem is a classic example of using SQL to generate rankings and order data based on certain criteria.
    Solution

Distributed Systems (11)

Easy (5)

Click for problems
  1. Nim Game - Problem #292
  2. Summary This problem illustrates game strategy in a distributed context, akin to making decisions in a distributed environment.
    Solution
  3. Flood Fill - Problem #733
  4. Summary This problem simulates the spread of information through cells, similar to data propagation in distributed systems.
    Solution
    class Solution:
        def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
            if image[sr][sc] == color:
                return image
            def dfs(row, col, startColor):
                if row < 0 or row >= len(image) or col < 0 or col >= len(image[0]) or image[row][col] != startColor:
                    return
                image[row][col] = color
    
            dfs(<span class="hljs-built_in">row</span> + <span class="hljs-number">1</span> , <span class="hljs-built_in">col</span>, startColor)
            dfs(<span class="hljs-built_in">row</span> - <span class="hljs-number">1</span>, <span class="hljs-built_in">col</span>, startColor)
            dfs(<span class="hljs-built_in">row</span>, <span class="hljs-built_in">col</span> + <span class="hljs-number">1</span>, startColor)
            dfs(<span class="hljs-built_in">row</span>, <span class="hljs-built_in">col</span> - <span class="hljs-number">1</span>, startColor)
        startColor = <span class="hljs-built_in">image</span>[sr][sc]
        dfs(sr, sc, startColor)
        <span class="hljs-built_in">return</span> <span class="hljs-built_in">image</span>
    

    Explanation

    1. Check if the newColor is the same as the color at the starting point (sr, sc). If they are the same, there's no need to perform the flood fill, so return the original image.

    2. Define a depth-first search (DFS) function, dfs, which takes the current row and column and the starting color as parameters. This function recursively explores neighboring pixels and changes their color to the newColor.

    3. Inside the dfs function:

      • Check if the current pixel is out of bounds or if it doesn't have the same color as the starting color. If any of these conditions are met, return, as there's no need to visit or change the color of this pixel.
      • Change the color of the current pixel to the newColor.
      • Recursively call dfs on the neighboring pixels in all four directions (up, down, left, right).
    4. Set the startColor variable to the color of the starting pixel (sr, sc).

    5. Call the dfs function to start the flood fill operation from the (sr, sc) point.

    6. Return the modified image after the flood fill is complete.

  5. To Lower Case - Problem #709
  6. Summary This problem demonstrates converting strings to lowercase, which is crucial in distributed systems for standardizing data formats.
    Solution
  7. Climbing Stairs - Problem #70
  8. Summary This problem compares to distributed problems with multiple paths, where optimizing traversal becomes essential.
    Solution
  9. Balanced Binary Tree - Problem #110
  10. Summary Balancing a binary tree is essential in distributed databases for optimizing data storage and retrieval.
    Solution

Medium (6)

Click for problems
  1. Network Delay Time - Problem #743
  2. Summary This problem mimics the propagation of information through a distributed network, similar to data transmission delays.
    Solution
  3. Number of Islands - Problem #200
  4. Summary This problem relates to distributed computation by simulating the spread of information through connected components in a grid.
    Solution
  5. Course Schedule - Problem #207
  6. Summary This problem reflects dependencies in distributed task scheduling, which is crucial for resource allocation
    Solution
  7. As Far from Land as Possible - Problem #1162
  8. Summary This problem involves measuring distances between nodes, similar to distance calculations in a distributed spatial context.
    Solution
  9. Rotting Oranges - Problem #994
  10. Summary This problem simulates distributed state changes and their propagation, similar to message passing in distributed systems.
    Solution
  11. Evaluate Division - Problem #399
  12. Summary This problem resembles graph traversal and calculations, which are often seen in distributed systems' computations.
    Solution

System Design and Architecture (10)

Easy (4)

Click for problems
  1. Design HashSet - Problem #705
  2. Summary

    In this problem, you're required to design a simple HashSet data structure, supporting basic operations like insertion, deletion, and checking for the presence of an element. While this problem might seem straightforward, it has some underlying connections to system design and architecture concepts:

    1. Data Modeling and Storage: When designing a HashSet, you need to think about how to organize and store the data efficiently. This can relate to database schema design in a larger system, where you would consider how to store and access data optimally.

    2. Data Access Optimization: In a larger system, quick access to data is crucial. When designing a HashSet, you're challenged to implement efficient lookup and manipulation operations, similar to how efficient data retrieval is a key consideration in designing systems.

    3. Collision Handling: Hash collisions can occur when multiple elements map to the same hash value. This connects to concepts of distributed systems and hashing techniques, which are relevant when handling data across multiple servers.

    4. Concurrency and Consistency: While the problem might not explicitly require it, in a distributed system, you would need to consider issues like concurrent access and maintaining data consistency. This mirrors challenges faced in distributed databases and systems.

    5. Scalability: While the problem doesn't specifically touch on this, when designing a HashSet for a large-scale system, you'd need to think about how to make the data structure scalable, possibly by sharding or partitioning data across different nodes.

    6. Data Integrity and Error Handling: Ensuring that your HashSet functions correctly and handles errors gracefully is akin to ensuring data integrity and handling exceptions in a real-world system.

    While this problem isn't a full-blown system design challenge, it provides a microcosm of considerations that come into play when designing and implementing data structures in a larger system. It's about making design choices that optimize for performance, reliability, and scalability—core tenets of system design and architecture.

    Problem

    Design a HashSet without using any built-in hash table libraries.

    Implement MyHashSet class:

    • void add(key) Inserts the value key into the HashSet.
    • bool contains(key) Returns whether the value key exists in the HashSet or not.
    • void remove(key) Removes the value key in the HashSet. If key does not exist in the HashSet, do nothing

    Example 1:

    Input

    ["MyHashSet", "add", "add", "contains", "contains", "add", "contains", "remove", "contains"]
    [[], [1], [2], [1], [3], [2], [2], [2], [2]]
    

    Output

    [null, null, null, true, false, null, true, null, false]
    

    Explanation

    MyHashSet myHashSet = new MyHashSet();
    myHashSet.add(1);      // set = [1]
    myHashSet.add(2);      // set = [1, 2]
    myHashSet.contains(1); // return True
    myHashSet.contains(3); // return False, (not found)
    myHashSet.add(2);      // set = [1, 2]
    myHashSet.contains(2); // return True
    myHashSet.remove(2);   // set = [1]
    myHashSet.contains(2); // return False, (already removed)
    

    Constraints:

    • 0 <= key <= 106
    • At most 104 calls will be made to add, remove, and contains.
    Solution
  3. Implement Queue using Stacks - Problem #232
  4. Summary This problem involves designing a queue using stacks. It tests your ability to create a data structure that emulates a queue's behavior using another data structure. Such design considerations are important when implementing efficient data processing pipelines.
    Solution
  5. Implement Queue using Stacks - Problem #225
  6. Summary Reinforces the concept of designing a queue using stacks, further illustrating the relationship between different data structures.
    Solution
  7. Next Greater Element I - Problem #496
  8. Summary This problem reinforces the concept of designing a queue using stacks, further illustrating the relationship between different data structures.
    Solution

Medium (6)

Click for problems
  1. LRU Cache - Problem #146
  2. Summary Designing a least recently used (LRU) cache involves managing data eviction strategies efficiently, which is crucial in system design where memory management and caching play a role.
    Solution
  3. Reorder Routes to Make All Paths Lead to the City Zero - Problem #1466
  4. Summary This problem simulates reordering routes in a directed graph to centralize paths. In system design, centralized data processing and communication can improve efficiency and reduce latency.
    Solution
  5. Min Stack - Problem #155
  6. Summary This problem requires designing a stack that supports constant-time retrieval of the minimum element. It relates to designing data structures that optimize for certain operations, which is a fundamental aspect of system design and architecture.
    Solution
  7. Count Unhappy Friends - Problem #1583
  8. Summary This problem requires designing a mechanism to count unhappy friends based on their preferences. This concept is similar to data analysis and pattern recognition in larger-scale systems.
    Solution
  9. Construct Binary Tree from Preorder and Inorder Traversal - Problem #105
  10. Summary In system design, constructing complex data structures efficiently from partial information can be crucial for optimization.
    Solution
  11. Accounts Merge - Problem #721
  12. Summary This problem involves designing a mechanism to merge user accounts, which is analogous to merging data and records in a larger system.
    Solution