Search⌘ K

Calculate String Length

Explore how to compute the length of a string through both iterative and recursive approaches in Python. This lesson helps you understand the underlying process, base cases, and performance considerations, enhancing your ability to use recursion effectively in coding challenges.

We'll cover the following...

In this lesson, we focus on the following problem:

Given a string, calculate its length.

If you are preparing for an interview or trying to understand the notion of recursion to solve a problem, I hope this lesson is helpful to you.

Python has a built-in len() function which returns the length of a string. This is the standard way to obtain the length of a string in Python.

Python 3.5
input_str = "LucidProgramming"
print(len(input_str))

Iterative Approach

Now we are going to code the same functionality ourselves in Python. Let’s begin with the iterative approach.

Python 3.5
# Iterative length calculation: O(n)
def iterative_str_len(input_str):
input_str_len = 0
for i in range(len(input_str)):
input_str_len += 1
return input_str_len

On line 3, input_str_len is initialized to 0. Then using a for loop on line 4, input_str is iterated character by character and input_str_len is incremented by 1 in each iteration on line 5. Finally, the final ...