0
0
DSA Pythonprogramming~30 mins

Remove Duplicates from Sorted Array Two Pointer in DSA Python - Build from Scratch

Choose your learning style9 modes available
Remove Duplicates from Sorted Array Using Two Pointers
📖 Scenario: You have a sorted list of numbers representing daily temperatures recorded over several days. Some temperatures are repeated because the sensor recorded the same temperature multiple times in a row. You want to clean this data by removing duplicate temperatures so that each temperature appears only once, keeping the order intact.
🎯 Goal: Build a program that removes duplicates from a sorted list of numbers using the two-pointer technique. The program should modify the list in place and print the cleaned list without duplicates.
📋 What You'll Learn
Create a list called temperatures with the exact values: [30, 30, 32, 32, 32, 35, 36, 36, 38]
Create a variable called write_index and set it to 1
Use a for loop with variable read_index starting from 1 to iterate over temperatures
Inside the loop, compare temperatures[read_index] with temperatures[write_index - 1]
If they are different, assign temperatures[read_index] to temperatures[write_index] and increment write_index by 1
After the loop, slice temperatures to keep only elements up to write_index
Print the final temperatures list
💡 Why This Matters
🌍 Real World
Cleaning sensor data or logs often requires removing repeated values to simplify analysis.
💼 Career
Understanding two-pointer techniques is useful for optimizing array and list operations in software development.
Progress0 / 4 steps
1
Create the sorted list of temperatures
Create a list called temperatures with these exact values: [30, 30, 32, 32, 32, 35, 36, 36, 38]
DSA Python
Hint

Use square brackets to create a list and include the numbers exactly as shown.

2
Set up the write pointer
Create a variable called write_index and set it to 1
DSA Python
Hint

This variable will track where to write the next unique temperature.

3
Use two pointers to remove duplicates
Use a for loop with variable read_index starting from 1 to iterate over temperatures. Inside the loop, compare temperatures[read_index] with temperatures[write_index - 1]. If they are different, assign temperatures[read_index] to temperatures[write_index] and increment write_index by 1. After the loop, slice temperatures to keep only elements up to write_index.
DSA Python
Hint

Use the two-pointer technique: one pointer reads through the list, the other writes unique values.

4
Print the cleaned list
Print the temperatures list after removing duplicates using print(temperatures)
DSA Python
Hint

Use print(temperatures) to show the cleaned list.