Leetcode Flashcards
Iterate over a list backwards
s = "hello" p = len(s) while p > 0: print(s[p]) p -= 1
- Max Subarray
Given an integer array nums, find the
subarray
with the largest sum, and return its sum.
Example 1:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: The subarray [4,-1,2,1] has the largest sum 6.
Use Kadane’s Algorithm.
Iterate over the list and add the numbers up, keeping a running_sum. Compare the running sum to a max_sum and take the highest. Whenever the running_sum is negative, set to 0.
Using continue vs pass
Remember that continue will exit out of the iteration and move on to the next - don’t execute the rest of the logic if you don’t need to
Initialize smallest and largest number placeholders
largest = float(‘inf’)
smallest = float(‘-inf’)
Reverse a list using slices
x = [1,2,3,4]
x[::-1]
How to calculate number of pairs in a list (i = j and i < j)
Input: nums = [1,2,3,1,1,3]
Output: 4
Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
To get the “# of pairs” for 3 repeated values, you would add the previous “# of times repeated” (which is 2) with the previous “# of pairs” (which is 1). Therefore, the “# of pairs for 3 repeated values is 2+1=3. In this method, you don’t peform the same computations multiple times.
In example, 1 shows up three times:
sum(range(0, 3) = 3
3 shows up twice:
sum(range(0, 2) = 1
Rotate an array by k elements
To the left: return arr[k:] + arr[:k]
To the right: return arr[-k:] + arr[:-k]
Use a deque to rotate any array by k elements
from collections import deque
d = deque(nums)
for i in range(0, k):
d.appendleft(d.pop())
nums[:] = d