avatarNaina Chaturvedi

Summary

The provided web content outlines a comprehensive guide on string data structures, their manipulation in Python, and their significance in coding interviews, along with a variety of related coding questions and solutions.

Abstract

The article delves into the concept of strings in programming, particularly in Python, emphasizing their importance in data structures and algorithms. It covers the basics of what strings are, how they work, and essential string methods such as indexing, slicing, and various string manipulation techniques. The author also discusses the relevance of strings in coding interviews and provides a collection of important string-related problems, including palindromes, valid parentheses, and finding the index of the first occurrence in a string. Additionally, the article offers tips and techniques for solving string questions efficiently and includes a list of other educational series and resources for readers interested in furthering their knowledge in data science, machine learning, and system design. The content is enriched with visual aids, code snippets, and links to additional learning materials, aiming to provide a thorough understanding of strings and their applications in practical projects.

Opinions

  • The author stresses the high importance of understanding strings and their manipulation for coding interviews and practical programming tasks.
  • They advocate for a hands-on approach to learning, suggesting that implementing string problems is crucial for mastering the concepts.
  • The article promotes the use of Python for string manipulation due to its readability and extensive library of string methods.
  • It suggests that readers should familiarize themselves with a hash map for parentheses matching and sliding window techniques for string problems.
  • The author encourages subscribing to their YouTube channel for video explanations and updates on new string questions with solutions.
  • They highlight the significance of system design base concepts and provide a list of system design articles as part of a complete system design series.
  • The author emphasizes the value of their newsletter for receiving tech interview tips, coding patterns, and updates on various technology projects.
  • They recommend following their other series and projects for a comprehensive understanding of Python, data science, machine learning, and more.

Day 12 of 30 days of Data Structures and Algorithms and System Design Simplified — Strings

Pic credits : Setscholars

Welcome back peeps. Hope all’s well. In this post we will cover Strings as follows —

What and Why Strings(in 2–3 sentences)?

How does Strings work?

Important Patterns and Techniques in Strings Questions

Most Important Questions with Solutions

Complexity Analysis

Tips and Techniques to solve Strings Questions Fast.

Projects Videos —

All the projects, data structures, SQL, algorithms, system design, Data Science and ML , Data Analytics, Data Engineering, , Implemented Data Science and ML projects, Implemented Data Engineering Projects, Implemented Deep Learning Projects, Implemented Machine Learning Ops Projects, Implemented Time Series Analysis and Forecasting Projects, Implemented Applied Machine Learning Projects, Implemented Tensorflow and Keras Projects, Implemented PyTorch Projects, Implemented Scikit Learn Projects, Implemented Big Data Projects, Implemented Cloud Machine Learning Projects, Implemented Neural Networks Projects, Implemented OpenCV Projects,Complete ML Research Papers Summarized, Implemented Data Analytics projects, Implemented Data Visualization Projects, Implemented Data Mining Projects, Implemented Natural Leaning Processing Projects, MLOps and Deep Learning, Applied Machine Learning with Projects Series, PyTorch with Projects Series, Tensorflow and Keras with Projects Series, Scikit Learn Series with Projects, Time Series Analysis and Forecasting with Projects Series, ML System Design Case Studies Series videos will be published on our youtube channel ( just launched).

Subscribe today!

System Design Case Studies — In Depth

Design Instagram

Design Messenger App

Design Twitter

Design URL Shortener

Design Dropbox

Design Youtube

Design API Rate Limiter

Design Web Crawler

Design Facebook’s Newsfeed

Design Yelp

Design Uber

Design Tinder

Design Tiktok

Design Whatsapp

Most Popular System Design Questions

Mega Compilation : Solved System Design Case studies

Strings

Importance : Very High

Day 2 of data structures and algorithms covers the topics that are most important and with highest ROI.

Let’s dive in!

What is Strings?

Python strings are arrays of bytes representing unicode characters. Strings in python are surrounded by either single quotation marks, or double quotation marks.

‘today’ is the same as “today”.

Example :

var1 = ‘Hello’

var2 = “Complete Python Course”

You can assign a multiline string to a variable by using three quotes.

Pic credits : brainmentors

Implementation —

str1 = "Welcome to complete Python Course"
str2 = 'Welcome to the complete Python Course'
str3 = """This is a
       multiline 
       String"""
print(str1)
print(str2)
print(str3)

Examples of Strings problems —

Longest Substring Without Repeating Characters

Longest Common Prefix

Longest Substring

Find subsequence

Word Search

Multiply strings

Analgrams

Palindromes

Reverse words

Isomorphic Strings

How does String work?

Strings are implemented as an array of characters with a special termination character, such as a null character, to indicate the end of the string. String manipulation functions and operators are commonly used to perform tasks such as concatenation, substring extraction, and search and replace operations on strings.

Some of the important String Methods that you should know —

String Indexing —

Pic credits : Stanford Edu

In python, Indexing is used to access individual characters of a string

Square brackets are used to access the character of the string using Index

Index starts with 0 , -1 refers to the last character, -2 refers to the second last character and so on

Example:

var[3]

var[-2]

String Slicing —

Pic credits : Setscholars

In python, Slicing is used to access a range of characters in the string. Slicing operator colon (:) is used

Example:

var[1:4]

var[:4]

Implementation —

s= "Captain America"
print(s[4])

Output —

a

Implementation 2 —

s= "Captain America"
print(s[1:5:2])

Output —

at

Implementation 3 —

print(s[::-1])

Output —

aciremA niatpaC

String Methods

  • split() : Splits String from Left

Implementation —

a = "Welcome,,Friends,"
print(a.split(","))

Output —

['Welcome', '', 'Friends', '']
  • splitlines() : Splits String at Line Boundaries
  • startswith() : Checks if String Starts with the Specified String
  • strip() : Removes Both Leading and Trailing Characters

Implementation —

a = "***Python***"
print(a.strip("*"))

Output —

Python
  • swapcase() : swap uppercase characters to lowercase; vice versa

Implementation —

a = "Hi Homies"
print(a.swapcase())

Output —

hI hOMIES
  • title() : Returns a Title Cased String
  • translate() : returns mapped charactered string
  • partition(sep) : Splits the string at the first occurrence of sep

Implementation —

a = "Complete.Python-course"
print(a.partition("-"))
print(a.partition("."))

Output —

('Complete.Python', '-', 'course')
('Complete', '.', 'Python-course')
  • isspace() : Checks Whitespace Characters

Implementation —

a = "\n\r"
print(a.isspace())

Output —

True
  • istitle() : Checks for Titlecased String
  • isupper() : returns if all characters are uppercase characters
  • join() : Returns a Concatenated String

Implementation —

a = ","
print(a.join("CD"))

Output —

C,D
  • ljust() : returns left-justified string of given width

Implementation —

x = "Python" 
y = x.ljust(10, "*")
print(y)

Output —

Python****
  • lower() : returns lowercased string
  • lstrip() : Removes Leading Characters

Implementation —

a = "*****Python-----"
print(a.lstrip("*"))

Output —

Python-----
  • maketrans() : returns a translation table
  • replace() : Replaces Substring Inside

Implementation —

a = "Welcome Aliens. Welcome to this world"
print(a.replace("Welcome", "Hi"))

Output —

Hi Aliens. Hi to this world
  • rindex() : Just like rfind() but raises ValueError when the substring sub is not found

Implementation —

a = "Hi World"
print(a.rindex("d"))
print(a.rindex("W"))

Output —

7
3
  • rjust() : returns right-justified string of given width
  • rstrip() : Removes Trailing Characters
  • upper() : returns uppercased string
  • zfill() : Returns a Copy of The String Padded With Zeros

Implementation —

a = "-124"
print(a.zfill(6))

Output —

-00124
  • capitalize() : Converts first character to Capital Letter

Implementation —

a = "complete python course" 
print(a.capitalize())

Output —

Complete python course
  • casefold() : converts to case folded strings

Implementation —

a = "PYTHON"
print(a.casefold())

Output —

python
  • center(): Pads string with specified character

Implementation —

a = "Python" 
b = a.center(10, "*")
print(b)

Output —

**Python**
  • index(): Returns Index of Substring

Implementation —

a = "Continent"
print(a.index("i"))
print(a.index("C"))
print(a.index("nent"))

Output —

4
0
5
  • isalnum(): Checks Alphanumeric Character

Implementation —

c = "456"
d = "$*%!!**"
print(c.isalnum())
print(d.isalnum())

Output —

True
False
  • isalpha() : Checks if All Characters are Alphabets

Implementation —

c = "456"
d = "Python"
print(c.isalpha())
print(d.isalpha())

Output —

False
True
  • isdecimal() : Checks Decimal Characters

Implementation —

c = u"\u00B10"
x = "10"
print(c.isdecimal())
print(x.isdecimal())

Output —

False
True
  • isdigit() : Checks Digit Characters

Implementation —

c = "4567"
d = "1.65"
print(c.isdigit())
print(d.isdigit())

Output —

True
False
  • isidentifier() : Checks for Valid Identifier

Implementation —

a = "_user/4567"
b = "for"
print(a.isidentifier())
print(b.isidentifier())

Output —

False
True
  • islower() : Checks if all Alphabets in a String are Lowercase
  • isnumeric() : Checks Numeric Characters
  • isprintable() : Checks Printable Character
  • count() : returns occurrences of substring in string

Implementation —

a = "Welcome to complete Python Course"
print(a.count("c"))
print(a.count("o"))
print(a.count("Python"))

Output —

2
5
1
  • encode() : returns encoded string of given string
  • endswith(): Checks if String Ends with the Specified Suffix

Implementation —

a = "Watermelon"
print(a.endswith("s"))
print(a.endswith("melon"))

Output —

False
True
  • expandtabs() : Replaces Tab character With Spaces
  • find(): Returns the index of first occurrence of substring

Implementation —

a = "Exercise"
print(a.find("r"))
print(a.find("e"))

Output —

3
2
  • format(): formats string into nicer output
  • format_map() : Formats the String Using Dictionary

Important Patterns and Techniques in String Questions

Strings function just like list i.e using indexing. So, along with strings methods mentioned above know how to manipulate string indexes and most importantly slicing.

Important patterns and techniques in string questions include regular expressions, string manipulation, and algorithms such as the Knuth-Morris-Pratt algorithm for string matching.

Patterns → Questions like below belong to Strings( not limited to):

Word Break

Shortest distance from one string to other

Longest Substring Without Repeating Characters

Longest Common Prefix

Longest Substring

Find subsequence

Word Search

Multiply strings

Analgrams

Palindromes

Reverse words

Isomorphic Strings etc

Most Important Questions with Solutions

Note : New String questions with solutions are added everyday. So keep checking this post daily.

Golden rule is — Learn by doing/implementing

In this we will see most important String questions.

Palindrome or not

Question —

A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.

Given a string s, return true if it is a palindrome, or false otherwise.

Example —

Input: s = "race a car"
Output: false

Solution:

Main Logic/Idea —

The main logic is to first check if the character at index t or v is alphanumeric or not. If not alphanumeric then keep incrementing/decrementing the pointers accordingly. Keep comparing the characters till t

Main Logic

Implementation —

class Solution:
    def isPalindrome(self, s: str) -> bool:
        t, v = 0,len(s)-1 
        
        while t<v :
            while t< v and not self.checkAlpha(s[t]):
                t+=1
            while v > t and not self.checkAlpha(s[v]):
                v -=1
            if s[t].lower() != s[v].lower():
                return False
            t,v = t+1,v-1
        return True
    
    def checkAlpha(self,n):
        return (ord('0') <= ord(n) <= ord('9') or
               ord('A') <= ord(n) <= ord('Z') or
               ord('a') <= ord(n) <= ord('z'))

Question Link

Similar Pattern —

Valid Palindrome II

Maximum Product of the Length of Two Palindromic Subsequences

Find First Palindromic String in the Array

Full Code Video Explanation ( In progress. Subscribe today for updates) :

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

Valid Parentheses

Question —

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.
  3. Every close bracket has a corresponding open bracket of the same type.

Example :

Input: s = "()[]{}"
Output : True

Solution :

Main Logic/Idea —

The main logic here is using hash map to map the close parentheses to open parentheses, append to the stack and using pop the similar match parentheses while traversing through the stack.

Main Logic

Implementation —

def isValid(self, s: str) -> bool:
        parenthesisMap  = { ")":"(", "]":"[", "}":"{" }
        ans = []
        
        for i in s:
            if i not in parenthesisMap:
                ans.append(i)
                continue
            if not ans or ans[-1] != parenthesisMap[i]:
                return False
            ans.pop()
        return not ans

Question Link

Similar Pattern —

Longest Valid Parentheses

Remove Invalid Parentheses

Check If Word Is Valid After Substitutions

Check if a Parentheses String Can Be Valid

Move Pieces to Obtain a String

Full Code Video Explanation ( In progress. Subscribe today for updates) :

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

Find the Index of the First Occurrence in a String

Question —

Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example :

Input: haystack = "sadbutsad", needle = "sad"
Output: 0

Solution :

Main Logic/Idea —

The main logic is know how to use index string method and once the index is found then return the index else return -1.

Main Logic

Implementation —

def strStr(self, haystack: str, needle: str) -> int:
        
        if needle in haystack :
            return haystack.index(needle)
        return -1

Question Link

Similar Pattern —

String Compression

Before and After Puzzle

Find All Good Strings

Full Code Video Explanation ( In progress. Subscribe today for updates) :

Tips and Techniques to solve Strings Questions Fast.

The most important thing to know before you solve any string question —

Strings methods ( covered above)

Sliding window

Recursion

Indexing and Slicing ( covered above)

That’s it for now. Day 13: Linked List coming soon !

Let me know if you have questions in the comment section below. Subscribe/ Follow, Like/Clap as it will encourage me to write more in my free time. Stay Tuned!!

Read More —

11 most important System Design Base Concepts

1. System design basics

2. Horizontal and vertical scaling

3. Load balancing and Message queues

4. High level design and low level design, Consistent Hashing, Monolithic and Microservices architecture

5. Caching, Indexing, Proxies

6. Networking, How Browsers work, Content Network Delivery ( CDN)

7. Database Sharding, CAP Theorem, Database schema Design

8. Concurrency, API, Components + OOP + Abstraction

9. Estimation and Planning, Performance

10. Map Reduce, Patterns and Microservices

11. SQL vs NoSQL and Cloud

12. Most Popular System Design Questions

13. System Design Template — How to solve any System Design Question

14. Quick RoundUp : Solved System Design Case Studies

Some of the other best Series —

60 days of Data Science and ML Series with projects

30 Days of Natural Language Processing ( NLP) Series

30 days of Machine Learning Ops

30 days of Data Structures and Algorithms and System Design Simplified

60 Days of Deep Learning with Projects Series

30 days of Data Engineering with projects Series

Data Science and Machine Learning Research ( papers) Simplified **

100 days : Your Data Science and Machine Learning Degree Series with projects

23 Data Science Techniques You Should Know

Tech Interview Series — Curated List of coding questions

Complete System Design with most popular Questions Series

Complete Data Visualization and Pre-processing Series with projects

Complete Python Series with Projects

Complete Advanced Python Series with Projects

Kaggle Best Notebooks that will teach you the most

Complete Developers Guide to Git

Exceptional Github Repos — Part 1

Exceptional Github Repos — Part 2

All the Data Science and Machine Learning Resources

210 Machine Learning Projects

Tech Newsletter —

If you are interested, you can join my newsletter through which I send tech interview tips, techniques, patterns, hacks — Software Development, ML, Data Science, Startups and Technology projects to more than 30K readers. You can subscribe to Tech Brew :

For Python Projects —

For complete 60 days of Data Science and ML : Day 1 — Day 60 : Quick Recap of 60 days of Data Science and ML

Follow for more updates. Stay tuned and keep coding!

For other projects, tune to —

Build Machine Learning Pipelines( With Code)

Recurrent Neural Network with Keras

Clustering Geolocation Data in Python using DBSCAN and K-Means

Facial Expression Recognition using Keras

Hyperparameter Tuning with Keras Tuner

Custom Layers in Keras

Programming
Software Development
Tech
Data Science
Machine Learning
Recommended from ReadMedium