House Robber Leetcode Solution Python

(Note: Robbing is against the law! 😉 The below is just the actual Leetcode question phrasing reproduced verbatim.)

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.

Constraints:

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 400

Leetcode Solution (Python)

class Solution:
    def rob(self, nums: List[int]) -> int:
        n = len(nums)
        # dp[i] max amount for nums[0:i]
        dp = [-1 for i in range(n+1)]
        
        # Recursive function that returns dp[i]
        def recursive(i):
            if i<=0:
                return 0
            if dp[i]!=-1:
                return dp[i]
            else:
                dp[i] = max(recursive(i-1), nums[i-1]+recursive(i-2))
            #print(dp)
            return dp[i]
        return recursive(n)

Cracking the Coding Interview: 189 Programming Questions and Solutions

Maximum Subarray Leetcode Solution Python

Given an integer array nums, find the subarray with the largest sum, and return its sum.

Leetcode Solution Python (Kadane’s Algorithm)

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        # Kadane's Algorithm
        max_sum = float('-inf')
        curr_sum = 0
        for i in range(0,len(nums)):
            curr_sum = max(nums[i], curr_sum+nums[i])
            max_sum = max(curr_sum, max_sum)
        return max_sum

Cracking the Coding Interview: 189 Programming Questions and Solutions

Best Time to Buy and Sell Stock Leetcode Python Solution

You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

Leetcode Python Solution

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        rolling_min = prices[0]
        max_profit = 0
        
        for i in range(0,len(prices)):
            curr_profit = prices[i]-rolling_min
            if curr_profit>max_profit:
                max_profit = curr_profit
            if prices[i]<rolling_min:
                rolling_min = prices[i]
                
        return max_profit

Elements of Programming Interviews in Python: The Insiders’ Guide

Leetcode Climbing Stairs Solution (Python)

You are climbing a staircase. It takes n steps to reach the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Constraints:

  • 1 <= n <= 45

Solution (Python)

class Solution:
    # dp[i] denotes number of ways for stairs with i steps
    dp = [-1 for i in range(45+1)]
        
    def climbStairs(self, n: int) -> int:
        # Base case
        if n<=1:
            return 1
        if self.dp[n]!=-1:
            return self.dp[n]
        # Recursive step
        self.dp[n] = self.climbStairs(n-1) + self.climbStairs(n-2)
        return self.dp[n]

Elements of Programming Interviews in Python: The Insiders’ Guide

Longest Common Prefix Leetcode Solution Python

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

Leetcode Solution (Python)

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        prefix = ''
        # Length of smallest string
        minlen = len(strs[0])
        for string in strs:
            if len(string)<minlen:
                minlen = len(string)
        
        for i in range(0,minlen):
            curr_char = strs[0][i]
            for string in strs:
                if string[i]!=curr_char:
                    return prefix
            prefix += curr_char
        
        return prefix

Elements of Programming Interviews in Python: The Insiders’ Guide

Implement strStr() Leetcode Solution Python

Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Leetcode Solution (Python)

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        n = len(needle)
        #print(needle)
        
        for i in range(0,len(haystack)-n+1):
            substr = haystack[i:i+n]
            #print(substr)
            if substr == needle:
                return i
            
        return -1

Elements of Programming Interviews in Python: The Insiders’ Guide

String to Integer (atoi) Leetcode Solution Python

Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer (similar to C/C++’s atoi function).

The algorithm for myAtoi(string s) is as follows:

  1. Read in and ignore any leading whitespace.
  2. Check if the next character (if not already at the end of the string) is '-' or '+'. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present.
  3. Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored.
  4. Convert these digits into an integer (i.e. "123" -> 123"0032" -> 32). If no digits were read, then the integer is 0. Change the sign as necessary (from step 2).
  5. If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then clamp the integer so that it remains in the range. Specifically, integers less than -231 should be clamped to -231, and integers greater than 231 - 1 should be clamped to 231 - 1.
  6. Return the integer as the final result.

Note:

  • Only the space character ' ' is considered a whitespace character.
  • Do not ignore any characters other than the leading whitespace or the rest of the string after the digits.

Leetcode Solution (Python)

class Solution:
    def myAtoi(self, s: str) -> int:
        # Positive sign
        positive = True
        result_str = ''
        digits = ['0','1','2','3','4','5','6','7','8','9']
        signs = ['+','-']
        
        # Has the first non-space been encountered
        started = False
        
        # Has the first sign been encountered
        signed = False
        
        for i in range(0,len(s)):
            if (signed == True or started == True) and s[i] in signs:
                break
            if s[i]!= ' ':
                started = True
                if s[i] in signs:
                    signed = True
                    if s[i]=='-':
                        positive = False
                elif s[i] in digits:
                    result_str += s[i]
            if started==True and s[i] not in digits and s[i] not in signs:
                break
            
            
        #print(result_str)
        if result_str=='':
            return 0
        else:
            result_int = int(result_str) if positive==True else -int(result_str)
            
        # Clamp Range:
        MIN_INT = -2**31
        MAX_INT = 2**31-1
        if result_int < MIN_INT:
            result_int = MIN_INT
        elif result_int > MAX_INT:
            result_int = MAX_INT
        
        return result_int

Elements of Programming Interviews in Python: The Insiders’ Guide

Valid Palindrome Leetcode Solution Python

A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.

Given a string s, return true if it is a palindrome, or false otherwise.

Leetcode Solution (Python)

class Solution:
    def isPalindrome(self, s: str) -> bool:
        # To lower case
        s = s.lower()
        
        # Remove puncutation
        s = s.translate(str.maketrans('', '', string.punctuation))
        
        # Remove space
        s = s.replace(" ", "")
        
        # Two pointers
        l = 0
        r = len(s)-1
        while l<r:
            if s[l]!=s[r]:
                return False
            l+=1
            r-=1
        
        return True

Elements of Programming Interviews in Python: The Insiders’ Guide

Valid Anagram Leetcode Solution Python (Beats 99.45% of Submissions)

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Leetcode Solution (Python)

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        # Set of characters in s,t
        charset_s = set(s)
        charset_t = set(t)
        
        # If the two sets differ, they are not anagrams
        if charset_s!=charset_t:
            return False
        
        for char in charset_s:
            # Count characters in s, t
            count_s = s.count(char)
            count_t = t.count(char)
            # If the counts differ, then they are not anagrams
            if count_s!= count_t:
                return False
        return True

Elements of Programming Interviews in Python: The Insiders’ Guide

Leetcode Reverse Integer Python Solution

Leetcode Question

Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.

Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

Python Solution

class Solution:
    def reverse(self, x: int) -> int:
        MAX_INT = 2**31-1
        MIN_INT = -2**31
        result = 0
        while x!=0:
            if result>MAX_INT/10 or result<MIN_INT/10:
                return 0
            digit = x%10 if x>0 else x%-10
            #print('digit:',digit)
            x = math.trunc(x/10)
            #print('x:',x)
            result = result*10 + digit
        return result

Cracking the Coding Interview: 189 Programming Questions and Solutions

Reverse String Leetcode Python Solution

Leetcode Question

Write a function that reverses a string. The input string is given as an array of characters s.

You must do this by modifying the input array in-place with O(1) extra memory.

Python Solution

class Solution:
    def reverseString(self, s: List[str]) -> None:
        """
        Do not return anything, modify s in-place instead.
        """
        l = 0
        r = len(s)-1
        while l<r:
            s[l],s[r] = s[r],s[l]
            l+=1
            r-=1

Cracking the Coding Interview: 189 Programming Questions and Solutions

Rotate Image Leetcode Solution Python

Rotate Image Leetcode

You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).

You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

Solution (Python)

class Solution:
    def rotate(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        n = len(matrix)
        # Transpose
        for i in range(0,n):
            for j in range(0,i):
                temp = matrix[i][j]
                matrix[i][j] = matrix[j][i]
                matrix[j][i] = temp
        #print(matrix)
        
        # Reflection (left-right, swap columns)
        for i in range(0,n):
            for j in range(0,n//2):
                temp = matrix[i][j]
                matrix[i][j] = matrix[i][n-j-1]
                matrix[i][n-j-1] = temp

Cracking the Coding Interview: 189 Programming Questions and Solutions

Valid Sudoku Leetcode Solution Python

Question

Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:

  1. Each row must contain the digits 1-9 without repetition.
  2. Each column must contain the digits 1-9 without repetition.
  3. Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.

Note:

  • A Sudoku board (partially filled) could be valid but is not necessarily solvable.
  • Only the filled cells need to be validated according to the mentioned rules.

Solution (Python)

class Solution:
    def checkRep(self, checklist):
        #print(checklist)
        for i in range(1,9+1):
            count = checklist.count(str(i))
            #print(i,count)
            if count>1:
                return False
        else:
            return True
        
    def getSquare(self,i_start,j_start,board):
        square_list = []
        for i in range(i_start,i_start+3):
            for j in range(j_start,j_start+3):
                square_list.append(board[i][j])
        return square_list
        
    def isValidSudoku(self, board: List[List[str]]) -> bool:
        # Check Rows
        for i in range(0,9):
            if self.checkRep(board[i])==False:
                return False
        
        # Check Columns
        for j in range(0,9):
            if self.checkRep([x[j] for x in board])==False:
                return False
        
        # Check Squares
        square_coords = []
        for i in range(0,3):
            for j in range(0,3):
                square_coords.append([i*3,j*3])
        #print(square_coords)
        for coord in square_coords:
            square_list = self.getSquare(coord[0],coord[1],board)
            if self.checkRep(square_list)==False:
                return False
        return True

Cracking the Coding Interview: 189 Programming Questions and Solutions

Move Zeroes Leetcode Python Solution

Question

Given an integer array nums, move all 0‘s to the end of it while maintaining the relative order of the non-zero elements.

Note that you must do this in-place without making a copy of the array.

Python Solution

class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        i=0
        num_zeros = 0
        while i<len(nums):
            #print(i)
            if i<=len(nums)-num_zeros:
                if nums[i]==0:
                    nums.pop(i)
                    nums.append(0)
                    num_zeros+=1
                else:
                    i+=1
            else:
                break

Cracking the Coding Interview: 189 Programming Questions and Solutions

Plus One Leetcode Solution Python

Question

You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0‘s.

Increment the large integer by one and return the resulting array of digits.

Solution (Python)

class Solution:
    def plusOne(self, digits: List[int]) -> List[int]:
        curr_index = len(digits)-1
        while curr_index>0:
            if digits[curr_index]<9:
                digits[curr_index] = digits[curr_index]+1
                return digits
            else:
                digits[curr_index] = 0
                curr_index -=1
        if curr_index==0:
            if digits[0]==9:
                digits[0]=0
                digits = [1] + digits
                return digits
            else:
                digits[0] = 1 + digits[0]
                return digits

Cracking the Coding Interview: 189 Programming Questions and Solutions

Intersection of Two Arrays II Leetcode Solution Python

Question

Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.

Solution (Python)

class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        len1 = len(nums1)
        len2 = len(nums2)
        smaller = nums1 if len1<=len2 else nums2
        larger = nums1 if len1>len2 else nums2
        #print(smaller)
        final_list = []
        for num in smaller:
            try:
                idx = larger.index(num)
                larger.pop(idx)
                final_list.append(num)
            except ValueError:
                pass
        return final_list

Cracking the Coding Interview: 189 Programming Questions and Solutions

Single Number Leetcode Solution Python

Question

Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.

You must implement a solution with a linear runtime complexity and use only constant extra space.

Solution (Python)

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        xor = 0
        for num in nums:
            xor ^= num
        # a^a = 0 (each number a, when xor with itself is 0)
        # 0^b = b (hence, the final output will return the element which appears only once)
        return xor

Cracking the Coding Interview: 189 Programming Questions and Solutions

Contains Duplicate Leetcode Solution Python

Question

Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.

Solution (Python)

class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        nums_set = set(nums)
        if len(nums)==len(nums_set):
            return False
        else:
            return True

Cracking the Coding Interview: 189 Programming Questions and Solutions

Rotate Array Leetcode Python Solution

Question

Given an integer array nums, rotate the array to the right by k steps, where k is non-negative.

Python Solution

class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        if k==0:
            return
        if k>=len(nums):
            k = k % len(nums)
        print('k:',k)
        right_list = nums[-k:] if k>0 else []
        left_list = nums[0:len(nums)-k]
        print('right_list:',right_list)
        print('left_list:',left_list)
        nums[:] = right_list + left_list

Cracking the Coding Interview: 189 Programming Questions and Solutions

Best Time to Buy and Sell Stock II Solution Python

Question

You are given an integer array prices where prices[i] is the price of a given stock on the ith day.

On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.

Find and return the maximum profit you can achieve.

Solution (Python)

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        profit = 0
        for i in range(0,len(prices)-1):
            if prices[i]<prices[i+1]:
                profit += prices[i+1]-prices[i]
        return profit

Cracking the Coding Interview: 189 Programming Questions and Solutions

Remove Duplicates From Sorted Array Leetcode Solution in Python

Question

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums.

Consider the number of unique elements of nums to be k, to get accepted, you need to do the following things:

  • Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. The remaining elements of nums are not important as well as the size of nums.
  • Return k.

Solution (Python)

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        final_list = []
        for num in nums:
            if num not in final_list:
                final_list.append(num)
        nums[:] = final_list
        k = len(nums)
        return k

Cracking the Coding Interview: 189 Programming Questions and Solutions