Beginner's Python for Leetcode
A beginners guide to strings and arrays in Python for Leetcode
Getting started with leetcode was a rough task for me. I’d open up the site all motivated, hyped to go on a problem solving rampage thinking the “easy” tag actually meant easy. However, I’d open up a question like 2sum and struggle to even understand the question and then just shut the site and leave out of frustration. Fast forward a year, and I’ve solved over 30 questions in just a week, building momentum that I didn’t think was possible back then. Here’s how I made it work.
I started with what I knew, lists and strings, which I’d learned in highschool. I hunted down questions where I could use these concepts, and I relied on loops, conditional statements, strings, and lists as my go-to tools.
In this guide, I’ll break down some of the most useful techniques I discovered for solving some basic string and array problems on LeetCode, starting from the basics and moving into strategies that can save you time and frustration.
A lot of string problems on LeetCode become easier once you know a few fundamental techniques and list functions. Here’s how I approach these problems and some of the functions I often rely on:
Iterating Through Lists: Many string problems involve checking or modifying individual characters. One of my go-to moves is to convert the string to a list (e.g., using
list(string)
) so I can easily modify each element.I often convert strings to lists or use lists directly for arrays so I can apply transformations. For instance, I’ll iterate through elements, look up values, or even count occurrences of specific elements.
Using Essential Functions:
count()
andindex()
: For frequency-based problems,count()
helps find the occurrence of an element, whileindex()
pinpoints specific positions, which is useful for both arrays and strings.append()
andextend()
: These functions are key when building arrays or modifying lists in place—great for problems that require forming new arrays or strings based on certain criteria.
Syntaxes:
count()
Syntax:
list.count(element)
Input: The element whose count you want to find.
Output: The number of occurrences of the element in the list.
nums = [1, 2, 2, 3]
count_of_twos = nums.count(2) # Output: 2
index()
Syntax:
list.index(element, start, end)
Input:
element
: The element to find.start
(optional): The starting index from which to search.end
(optional): The ending index up to which to search.Output: The index of the first occurrence of the element. Raises a
ValueError
if the element is not found.
nums = [1, 2, 3, 2]
index_of_two = nums.index(2) # Output: 1
append()
- Syntax:
list.append(element)
nums = [1, 2, 3]
nums.append(4) # nums is now [1, 2, 3, 4]
extend()
- Syntax:
list.extend(iterable)
nums = [1, 2]
nums.extend([3, 4]) # nums is now [1, 2, 3, 4]
One challenge I encountered was converting the data type of each element in a list. Initially, I would iterate through the entire list and append the converted values to a new list, which was quite time-consuming.
I later discovered the map
function, which allowed me to efficiently change the data type of each element. And the join function, which concatenates the elements.
map()
- Syntax:
map(function, iterable)
nums = ['1', '2', '3']
converted_nums = list(map(int, nums)) # Output: [1, 2, 3]
join()
Syntax:
separator.join(iterable)
Input:
separator
: A string that will be placed between elements.iterable
: An iterable containing the strings to be joined.Output: A single string formed by concatenating the elements of the iterable with the separator.
char_list = ['h', 'e', 'l', 'l', 'o']
result = ''.join(char_list) # Output: "hello"
A combination of both of these functions proved to be very useful.
1. Using ''.join(map(str, list))
to Concatenate Integers into a String
One scenario where I found ''.join(map(str, list))
particularly helpful was when I needed to concatenate a list of integers into a single string. For instance, imagine I had a list of digits that I wanted to turn into a continuous number.
# Given a list of integers
digit_list = [1, 2, 3, 4, 5]
# Using ''.join(map(str, digit_list)) to concatenate the integers into a string
result = ''.join(map(str, digit_list))
print(result) # Output: "12345"
In this example, I started with a list of integers, digit_list
, containing the digits of a number. Instead of iterating through each element, converting them to strings, and appending them to a new list, I used map(str, digit_list)
to convert each integer to a string in one go.
Then, I applied ''.join()
to combine these string elements into a single string. The result was the string "12345", which represents the concatenated digits. This method not only saved me time but also made my code cleaner and more efficient.
2. Using sum(map(int, list))
to Sum a List of Number Strings
Another situation where I found the power of sum(map(int, list))
helpful was when I needed to sum a list of number strings. Let’s say I had a list of strings, each representing a numeric value, and I wanted to compute their total.
# Given a list of strings representing numbers
string_list = ["1", "2", "3", "4", "5"]
# Using sum(map(int, string_list)) to calculate the total
total = sum(map(int, string_list))
print(total) # Output: 15
In this example, I started with a list of strings, string_list
, where each string corresponds to a digit. Instead of manually converting each string to an integer through iteration and appending them to a new list, I used map(int, string_list)
to convert all the string elements to integers at once.
Then, I applied sum()
to calculate the total of these integers. The result was 15, which is the sum of all the numbers in the original list. This method significantly streamlined my code, eliminating unnecessary loops and making it much more efficient.
Additionally, I encourage you to learn more functions and understand how they work. The more tools you have in your programming toolbox, the easier it will be to come up with solutions and save time as well. The more in depth you learn these, it will help making your work more efficient.
Final Thoughts
As you embark on your own journey with coding challenges, I have a piece of advice that can make a significant difference: Read the questions slowly. Take your time to understand what’s being asked. If needed, write it down on paper and visualize your ideas. This approach can help you clarify your thoughts and identify how different functions can be applied effectively.
Try to find patterns in the problems you encounter and think about how you can apply the functions discussed above. Visualize what will happen if you implement your solution, considering how the data will flow through your functions and what transformations will take place at each step. This mental mapping can often reveal new insights and lead you to more efficient solutions.
Subscribe to my newsletter
Read articles from Arjun Patil directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by