Sitemap
Giridhar Sharma

Giridhar Sharma

Data Engineer with 10+ Years of Experience working with MNCs to build robust and scalable data products

Problem Solving: Substring problems in Python

2 min readAug 23, 2023

--

This article focuses on how to solve the string problems. This article outlines my learning’s. There must me multiple ways to solve the same problems, my objective is to explain my learnings in best possible way.

Problem Statement: Given a string x, find the length of the longest sub sting without repeating characters.

Initial thoughts: The problem statement is easy to understand, when we breakdown the problem we run into some scenarios

  1. The string is Null, if that is the case I expect the output to be 0.
  2. The string is non repeating string, in such case the output will be length of the sting.
  3. The string is repeating string, the repetition can be in multiple ways, eg: abcbcdecde output: 3 abcabcdeabc output:5

For implementation, lets take the point 1. It can be solved easily by defaulting the output to be 0.

For identifying the substring, we would need two pointers. First one should point to the first character of non repeating substring and second one should be pointing to the last non repeating character of the substring.

Get Giridhar Sharma’s stories in your inbox

Join Medium for free to get updates from this writer.

There is also a need of a output variable that should change if the current substring is longer than previous one.

For the implementation, We will initiate three objects

  1. Word_Dict: This object will store each alphabet & the most recent position. It will help us to check if the word is repeating
  2. StartPoint: This pointer will help us to calculate the length of the substring
  3. Length: This variable will contain the maximum length of the substring.
class Solution:
@staticmethod
def lengthOfLongestSubstring(s):
if not s:
return 0

Word_Dict = {}
Length = 0
StartPoint = 0

for end in range(len(s)):
if s[end] in Word_Dict and StartPoint <= Word_Dict[s[end]]:
StartPoint = Word_Dict[s[end]] + 1
else:
max_length = max(max_length, end - StartPoint + 1)
Word_Dict[s[end]] = end

return max_length

This technique can be used for other String problems as well where we need to maintain two pointers.

Thanks for reading this article. Consider giving me claps!!

अलविदा !

Press enter or click to view image in full size

--

--

Giridhar Sharma
Giridhar Sharma

Written by Giridhar Sharma

Data Engineer with 10+ Years of Experience working with MNCs to build robust and scalable data products