- Published on
Python Leetcode Walkthrough Part 1
- Authors
- Name
- Vishal Soomaney
- @VSoomaney
Problem: Reverse a list Problem 1 - Difficulty Level: Super Easy
An example array: test_list = [1, 2, 3, 4, 5]
There are several ways of easily reversing this.
Option 1: The reverse() function
test_list.reverse() # Built-in Python in-place reversal function
# validate the code worked as expected
assert test_list == [5, 4, 3, 2, 1]
The main issue with this is that it doesn't actually show what's happening behind the scenes causing the reversal to take place so doesn't really showcase any skill.
Option 2: Slicing
test_list = test_list[::-1]
# validate the code worked as expected
assert test_list == [5, 4, 3, 2, 1]
- Slicing works the same for both lists and strings.
- The syntax is test_list[start:stop:step]
- In this case we want to use the default start location (index 0) and default end location (index len(test_list)-1) hence go through the entire array
- We however want to step through it in reverse, so we'd step through 5 then 4 then 3 with the new array being [5,4,3,2,1] This method shows knowledge of slicing and general Pythons skills whilst being just as fast but slightly less readable as the reverse() option.
Option 4: A simple for loop
def reverse_list(current_list: list) -> list:
new_list = []
for number in current_list:
new_list.insert(0, number)
return new_list
assert reverse_list(test_list) == [5, 4, 3, 2, 1]
Problem: Return every even number in a list Problem 2 - Difficulty Level: Easy
events_list = []
for number in test_list:
if number % 2 == 0:
evens_list.append(number)
Problem 3 - Difficulty Level: Medium
Initial way of visualising the problem (by character index) where numRows == 6:
0 n+5 (10) == 2n-2
1 n+4 n+6 (11)
2 n+3 n+7 (12)
n-2 n+2 n+8 (13)
n-1 n+1 n+9 (14)
n n+10 (15)
Any algorithm we design for this should start with base cases:
if numRows == 1 or numRows >= len(s):
return s
To explain this:
- If there is only one row then all characters will remain in the same order.
- If the number of rows is greater than or equal to the length of the string, each character in the string will end up in a separate row. This will then get joined together into the same string in the same order:
s = abc
numRows =3
rows = [
"a",
"b",
"c"
]
final_string = ''.join(rows)
assert final_string == s
Walking through the string->zigzag transition in words:
- Up until the nth character, each character is split into a separate row.
- Between the nth character and the 2n-2 character, each character goes back up a row.
outcome = ['' for row in range(numRows)] # Creating an array with an entry for each row.
row = 0
direction = 1 # +1 to keep going down, -1 to go up
for char_index in range(len(s)):
outcome[row] += s[char_index]
if row == numRows-1 or row == 0:
direction *= -1 # Switch directions
row += direction
''.join(outcome)