avatarNaina Chaturvedi

Summary

The provided content outlines the two-pointer technique, a programming approach used to solve problems involving arrays and lists, and includes tutorials, patterns, and questions with solutions.

Abstract

The web content titled "Day 8 of 30 days of Data Structures and Algorithms and System Design Simplified — Two Pointer Technique" delves into the two-pointer technique, which is a programming strategy that employs two pointers to track and process elements within an array or list. The article covers the concept's importance, how it works, and its application through patterns and techniques. It also provides examples of common problems that can be solved using this technique, such as the "Container With Most Water" problem. The content includes detailed explanations, implementation tips, and links to additional resources and video explanations. Furthermore, it emphasizes the significance of the two-pointer technique in optimizing algorithms by saving space and time, and it encourages readers to engage with the material by solving practice questions.

Opinions

  • The author believes that understanding the two-pointer technique is crucial for solving certain types of programming problems efficiently.
  • The article suggests that learning by doing, specifically through implementing solutions to problems, is a highly effective educational approach.
  • The content promotes the idea that mastering this technique can lead to a higher return on investment in terms of time spent learning.
  • It is implied that the two-pointer technique is versatile and can be applied to a variety of scenarios, including those involving linked lists and arrays.
  • The author encourages continuous learning and practice by providing a series of related problems and promising to add new questions regularly.
  • The article positions the two-pointer technique as a fundamental skill for system design and algorithm optimization.
  • It is conveyed that subscribing to the associated YouTube channel, Ignito, will provide additional educational content and coding exercises.
  • The author expresses a commitment to providing comprehensive learning resources, including projects, data structures, algorithms, system design, and more.

Day 8 of 30 days of Data Structures and Algorithms and System Design Simplified — Two Pointer Technique

Pic credits : github

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

What and Why Two pointer technique(in 2–3 sentences)?

How does Two pointer technique work?

Important Patterns and Techniques in Two pointer technique Questions

Most Important Questions with Solutions

Complexity Analysis

Tips and Techniques to solve Two pointer technique 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

Two pointer Technique

Importance : Very High

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

Note : New Two pointer technique questions with solutions will be added everyday. So keep checking this post everyday.

Let’s dive in!

What is Two pointer technique?

Two pointer is a technique in which two pointers ( references) are used to keep a track of array/string indices. They are streamlined so that they can iterate the two parts of the array simultaneously.

It’s a useful technique to utilize when searching for pairs in sorted array.

Using two pointer technique you can save space and time and optimize your algorithm.

Within one loop two elements are accessed and processed simultaneously. There are two approaches in two pointer technique —

Start and End Two pointers — One pointer starts from the beginning while the other pointer starts from the end , until they meet.

Slow and fast pointers— One slow-runner ( moves at slower pace) and the other fast-runner ( moves twice the speed of the slow pointer).

Pic credits : Pluralsight

Examples of Two pointer technique based problems —

Remove Duplicates from Sorted Array

Find “Nth” node in the linked list

Two Sum II — Input array is sorted

Two Sum III — Input array is sorted

Reverse Words in a String II

Rotate Array

Valid Palindrome

Container With Most Water

Product of Array Except Self

How does Two pointer technique work?

Two pointer technique is a method used to solve problems involving arrays and lists by moving two pointers through the data structure, one pointer moving forward and the other moving backward. It is used to find a pair of elements that meet a certain condition, or to find the smallest or largest sub-array.

The Two pointer technique works by having a “left” pointer and a “right” pointer. The left pointer starts at the beginning of the array, and the right pointer starts at the end. The pointers are then moved towards each other based on a certain condition. The condition can be the sum of the elements at the pointers is equal to a target value or the difference between the two pointers is equal to a target value.

Start and End pointers —> Left and Right Pointers:

One pointer starts from the beginning while the other pointer starts from the end, until they meet.

Pic credits : afteracad

Slow and Fast Pointer :

One slow-runner ( moves at slower pace) and the other fast-runner ( moves twice the speed of the slow pointer).

Pc credits : codebus

Important Patterns and Techniques in Two pointer Programming Questions

Important patterns and techniques in Two pointer technique questions include understanding how to use two pointers to solve problems, analyzing the time and space complexity of the solution, identifying the correct condition for moving the pointers, and handling edge cases like empty input or input with negative values.

1.End pointers — Left and Right Pointers

In case of left and right pointers, start by iterating the left pointer one element at a time from the first element and right element from the end. Evaluate the condition and increment or decrement the pointers accordingly.

2. Left and Right Pointers — Sliding window

Left and Right pointers start from the first element and keep sliding as per the requirement ( i.e based on the target condition).

3. Slow and Fast Pointer

Slow pointer moves by one element and fast pointer moves twice the speed i.e by two elements starting from the first index of the array until they meet.

Patterns → Questions like below belong to Two pointer technique ( not limited to):

Delete N Nodes After M Nodes of a Linked List

Delete the Middle Node of a Linked List

Remove Duplicates from Sorted Array

Two Sum II — Input array is sorted

Reverse Words in a String II

Rotate Array

Valid Palindrome

Container With Most Water

Product of Array Except Self etc

Most Important Questions with Solutions

Note : New two pointer technique based questions with solutions are added every day. So keep checking this post day.

Golden rule is — Learn by doing/implementing

In this we will see most important Two pointer technique based questions.

Container With Most Water

Question —

You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).

Find two lines that together with the x-axis form a container, such that the container contains the most water.

Return the maximum amount of water a container can store.

Example :

Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49

Solution :

Main Logic/Idea —

The main logic is to take two pointers left ( start of the array) and right ( end of the container heights and a maxarea variable to store the current area. Calculate the area and update the maxarea pointer.

Keep incrementing left pointer/decrementing right pointer if height pointed by left pointer is less than the height pointed by the right pointer. Keep updating the maxarea.

Main Logic

Implementation —

def maxArea(self, height: List[int]) -> int:
        left,right,ans = 0,len(height)-1, 0
        
        while left < right :
            ar = (right- left) * min(height[left],height[right])
            ans = max(ans,ar)
            
            if height[left] < height[right]:
                left +=1
            else:
                right -=1
        return ans

Question Link

Similar Pattern —

Minimum Incompatibility

Count Items Matching a Rule

Broken Calculator

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

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

Remove Nth Node From End of List

Question —

Given the head of a linked list, remove the nth node from the end of the list and return its head.

Example :

Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]

Solution :

Main Logic/Idea —

The main idea is — take two pointers and keep incrementing till you find the one node prior to the target node ( left pointer) while right pointer will pointer will go on till the end to store the address of next node pointed by the node to be removed. Once done, point left.next to left.next.next to remove the target node.

Main Logic

Implementation —

def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        temp =ListNode(0,head)
        left = temp
        right = head
        
        while n>0 and right:
            right = right.next
            n -=1
            
        while right:
            left =left.next
            right = right.next
        
        left.next = left.next.next
        return temp.next

Question Link

Similar Pattern —

Delete N Nodes After M Nodes of a Linked List

Delete the Middle Node of a Linked List

Swapping Nodes in a Linked List

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

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

Linked List Cycle

Question —

Given head, the head of a linked list, determine if the linked list has a cycle in it.

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.

Return true if there is a cycle in the linked list. Otherwise, return false.

Example 1:

Input: head = [3,2,0,-4], pos = 1
Output: true

Solution :

Main Logic/Idea —

The main logic — Take two pointers, one slow at x speed and other fast at 2x speed. Start traversing from the first node and increment slow by one node and fast pointer by two nodes. If slow pointer meets fast pointer then return True (i.e cycle exists in the linked list) else False.

Main Logic

Implementation —

def hasCycle(self, head: Optional[ListNode]) -> bool:
        slow, fast = head, head
        
        while fast and fast.next :
            slow= slow.next 
            fast = fast.next.next 
            if slow == fast:
                return True 
        return False

Question Link

Similar Pattern —

High Five

Keep Multiplying Found Values by Two

Design HashMap

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

Tips and Techniques to solve Two pointer Questions Fast —

To solve the Two pointer technique based questions fast —

  1. Know how to iterate/move the indexes efficiently.
  2. Learn the patterns as covered in this post above.
  3. Refer to sliding window post to understand how to use two pointers to move along the slide.

Most important two pointer technique based questions —

Remove Duplicates from Sorted Array

Two Sum II — Input array is sorted

Reverse Words in a String II

Rotate Array

Valid Palindrome

Container With Most Water

Product of Array Except Self

That’s it for now. Day 9: Recursion 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 and 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
Tech
Software Development
Machine Learning
Data Science
Recommended from ReadMedium
avatarAbhay Kumar
OOPs in Python

An easy guide

10 min read