Leetcode Flashcards

1
Q

Iterate over a list backwards

A
s = "hello"
p = len(s)
while p > 0:
    print(s[p])
    p -= 1
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q
  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.

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Using continue vs pass

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Initialize smallest and largest number placeholders

A

largest = float(‘inf’)

smallest = float(‘-inf’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Reverse a list using slices

A

x = [1,2,3,4]
x[::-1]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

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.

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Rotate an array by k elements

A

To the left: return arr[k:] + arr[:k]
To the right: return arr[-k:] + arr[:-k]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Use a deque to rotate any array by k elements

A

from collections import deque
d = deque(nums)

for i in range(0, k):
d.appendleft(d.pop())
nums[:] = d

How well did you know this?
1
Not at all
2
3
4
5
Perfectly