🚀 Day 2 – DSA Series Remove Duplicates from Sorted Array Solved LeetCode 26 – Remove Duplicates from Sorted Array using Python. 🧠 Problem Summary Given a sorted array nums, remove duplicates in-place such that each unique element appears only once. Return the number of unique elements k, where: • The first k elements of nums contain the unique values • The remaining elements beyond k don’t matter • No extra array allowed (O(1) space) Example: Input: [1, 1, 2] Output: k = 2 → Modified array: [1, 2, _] 💡 Approach Used (Two Pointer Technique) Since the array is sorted, duplicates are adjacent. ✔️ Initialized k = 1 (first element always unique) ✔️ Iterated from index 1 ✔️ Compared current element with previous element ✔️ When a new unique element is found: • Placed it at index k • Incremented k This ensures in-place modification without extra space. ⏱ Complexity Analysis Time Complexity: O(n) – single pass Space Complexity: O(1) – no additional data structures 🔎 Key Takeaway This problem strengthens: • Two Pointer pattern • In-place array manipulation • Understanding problem constraints carefully Continuing the DSA series — one problem at a time. 🚀 #DSA #LeetCode #Python #Algorithms #TwoPointers #ProblemSolving #CodingJourney
Remove Duplicates from Sorted Array in Python
More Relevant Posts
-
🚀 Day 4 – DSA Daily Series Move Zeroes (LeetCode 283) using Python. 🧠 Problem Given an integer array nums, move all 0’s to the end of the array while maintaining the relative order of the non-zero elements. Important constraints: • The operation must be done in-place • No extra array should be created Example: Input: nums = [0,1,0,3,12] Output: [1,3,12,0,0] 💡 Approach Used the Two Pointer technique. • Maintain a pointer k to track the position for the next non-zero element • Traverse the array using index i • Whenever a non-zero element is found, swap it with the element at position k • Increment k This ensures: • Non-zero elements move to the front • Zeros automatically shift toward the end ⏱ Complexity Time Complexity: O(n) – single pass through the array Space Complexity: O(1) – in-place modification 🔎 Key Learning This problem helps strengthen: • Two Pointer pattern • In-place array manipulation • Maintaining relative order while rearranging elements Consistency is key when practicing DSA — solving one problem at a time. 🚀 #DSA #LeetCode #Python #Algorithms #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 1 – DSA Series Two Sum (LeetCode) Starting my DSA problem-solving series with the classic Two Sum problem, implemented in Python. 🧠 Problem Statement Given an integer array nums and an integer target, return the indices of the two numbers such that they add up to the target. Constraints: • Exactly one valid solution exists. • The same element cannot be used twice. • The answer can be returned in any order. Example: nums = [2, 7, 11, 15], target = 9 Output: [0, 1] Because 2 + 7 = 9. 💡 Approach Implemented I used the nested loop (brute force) approach: • Iterate through each element • Check all remaining elements • Return indices when sum equals target ⏱ Complexity Analysis Time Complexity: O(n²) Space Complexity: O(1) Even for a well-known problem, breaking it down step by step helps strengthen logical thinking and reinforces core fundamentals before jumping to optimized solutions. I’ll be solving and sharing one DSA problem daily -focusing on clarity, approach, and complexity analysis. Let’s build consistency. 🚀 #DSA #LeetCode #Python #Algorithms #ProblemSolving #SoftwareEngineering #CodingJourney
To view or add a comment, sign in
-
-
🧠 Python Concept: List Comprehension Write powerful loops in one clean line. ❌ Traditional Way squares = [] for i in range(5): squares.append(i * i) print(squares) Output [0, 1, 4, 9, 16] ✅ Pythonic Way squares = [i * i for i in range(5)] print(squares) Same result, less code. ⚡ With Condition even_squares = [i * i for i in range(10) if i % 2 == 0] print(even_squares) Output [0, 4, 16, 36, 64] 🧒 Simple Explanation Imagine telling a robot: 👉 “Give me squares of numbers from 0–4.” 👉 Instead of repeating instructions, you give one rule. 👉 That rule = list comprehension. 💡 Why This Matters ✔ Shorter code ✔ Faster execution ✔ More readable loops ✔ Very Pythonic 🐍 Python often replaces multiple lines with a single elegant expression 🐍 List comprehensions are one of the most powerful examples of that philosophy. #Python #PythonTips #PythonTricks #AdvancedPython #List #ListComprehension #Tech #CleanCode #LearnPython #Programming #DeveloperLife #DailyCoding #100DaysOfCode
To view or add a comment, sign in
-
-
Today I implemented Serialize and Deserialize Binary Tree in Python. The goal of the problem is to convert a binary tree into a string so it can be stored or transferred, and later reconstruct the exact same tree from that string. I used a BFS (level order traversal) approach for this. Idea: • Traverse the tree level by level using a queue. • Store node values in a list. • For missing children, store a special marker (#) so the structure of the tree is preserved. • Join the list into a single string. For deserialization, the process is reversed: • Split the string back into values. • Rebuild the tree using a queue. • Attach left and right children in the same order they were stored. What I liked about this problem is that it shows how important it is to preserve structure, not just values. Without storing null nodes, reconstructing the same tree would be impossible. Time Complexity: O(N) Space Complexity: O(N) Problems like this are a good reminder that tree problems often combine traversal, data representation, and careful reconstruction logic. #DSA #BinaryTree #Python #Algorithms #CodingInterview
To view or add a comment, sign in
-
-
Pyramids in Python print('\nNormalPyramid')for i in range(5): x='*' x=x*i print(f'{x:^10}')print('\nInvertPyramid\n')for i in range(5): x='*' x=x*(5-i) print(f'{x:^10}')print('Left sided Pyramid')rows = 5for i in range(1, rows + 1): stars = '*' * i print(f'{stars:<10}')print('\nRightsidedPyramid') rows = 5for i in range(1, rows + 1): spaces = ' ' * (rows - i) stars = '*' * i print(f'{spaces}{stars}')#pythoncode
To view or add a comment, sign in
-
-
Day 40 of my #100DaysOfCode challenge 🚀 Today I implemented the Merge Sort algorithm in Python. Merge Sort is a powerful divide-and-conquer algorithm that divides the list into smaller parts, sorts them, and then merges them back together. What the program does: • Takes an unsorted list as input • Recursively divides the list into halves • Sorts each half separately • Merges the sorted halves into a final sorted list How the logic works: • If the list has 1 or 0 elements, it is already sorted (base case) • The list is divided into two halves using the middle index • Each half is recursively sorted using merge_sort() • A helper function merge() combines the two sorted halves • Elements are compared and merged in sorted order • Remaining elements are appended after comparison Example: Input: [38, 27, 43, 3, 9, 82, 10] Output: [3, 9, 10, 27, 38, 43, 82] Why Merge Sort is powerful: – Time Complexity: O(n log n) – Efficient for large datasets – Stable sorting algorithm – Widely used in real-world applications Key learnings from Day 40: – Understanding divide-and-conquer strategy – Writing recursive functions – Merging sorted arrays efficiently – Moving towards advanced DSA concepts #100DaysOfCode #Day40 #Python #PythonProgramming #MergeSort #SortingAlgorithms #DataStructures #Algorithms #DivideAndConquer #ProblemSolving #CodingPractice #InterviewPrep #BTech #CSE #AIandML #VITBhopal #TechJourney
To view or add a comment, sign in
-
-
In Python, everything is an object. That one fact broke my mental model this week. I'm transitioning from Software engineering to AI engineering. Week 1, Day 7 🗓️ Here's what clicked 😲. Since everything in Python is an object, every object has a unique memory address. Dict uses this to store and find values in O(1). It hashes the key, jumps directly to the slot. No scanning. No searching. But this only works if the key never changes. A mutable key changes its hash, changes its slot, and your value becomes permanently unreachable. Silent corruption 🤯 . So dict keys must be immutable. And immutable means hashable. Hashable objects carry two methods that work as a pair: __hash__() generates the slot number & __eq__() confirms the exact key at that slot. Override one without the other and Python punishes you: ``` class BrokenDog: def __eq__(self, other): return self.name == other.name # forgot __hash__ hash(BrokenDog("Rex")) # ❌ TypeError: unhashable type ``` But Python's built-in types like dict and str already override __eq__() to compare contents and not addresses. That's why two dicts with identical keys and values return True on `==`. One more thing that surprised me. Since every object in Python carries this overhead of creation, hashing, and storage, even a simple `int` is not free. That's exactly why NumPy exists to escape Python's object model and work directly with raw memory for numerical computation. For more details, refer: https://lnkd.in/gZCGFRBB What's the Python concept that surprised you most when you first learned it? #AIEngineering #Python #LearningInPublic #CareerTransition #SoftwareEngineering
To view or add a comment, sign in
-
INSTEAD OF WASTING TIME AND TRYING TO GET FIGURES. WHY NOT USING CODE?? Sometimes, lecturers or organizations need to generate different sets of questions for multiple candidates, especially when working with matrices. However, this often requires a lot of manual effort and can be time-consuming. Why not simplify the process using NumPy in Python? With just a few lines of code, you can easily generate multiple variations of matrix-based questions efficiently and save valuable time. #randint is an inbuilt function of the random module of numpy #Syntax: np.random.randint(start, stop (rows, columns)) a=np.random.randint(2,30, (3,3)) b=np.random.randint(2,30, (3,3)) c=np.random.randint(2,30, (3,3)) d=np.random.randint(2,30, (3,3)) e=np.random.randint(2,30, (3,3)) #DataScience #Python #NumPy #Education #Automation
To view or add a comment, sign in
-
-
Last week I shared results from an ABRF-LMRG study suggesting a large increase in inter-analyst variability when comparing Imaris/Arivis/Aivia workflows to Python/ImageJ/CellProfiler workflows. I also started a discussion on Image.sc to explore possible causes. It turns out a major contributor to the apparent variability was small mistakes in the code used to generate the plots. The original plot from the paper is on the left, with a corrected plot on the right. Comparing image analysis outputs is inherently challenging—differences in conventions like x/y ordering, units (microns vs. pixels), and even simple naming inconsistencies can introduce errors. The authors had intended to correct for these issues, but some datasets were not adjusted for x–y mix-ups and pixel-to-micron conversions. After fixing these issues in the code, the results change substantially: the Imaris/Arivis/Aivia and Python/ImageJ/CellProfiler solutions are much closer, and the previously observed order-of-magnitude differences (on a log scale) are no longer present. There may still be a real signal—Python/ImageJ/CellProfiler results appear slightly more variable, spanning both the best and worst scores—but the very large errors initially observed are no longer present in the plot.
To view or add a comment, sign in
-
-
Most Python workflows rely on heuristics. They’re quick, intuitive, but usually not optimal. A simple greedy approach might get you a solution, but it often leaves efficiency, performance, and cost savings on the table. GAMSPy brings algebraic modeling into Python, so you can express constraints and objectives directly and solve for a true optimum. At PyConDE & PyData 2026, Justine Broihan and Muhammet Soyturk will walk through this using a classic operations example, and then extend it into machine learning. They'll cover: 🔸 How optimization compares to rule-based heuristics and 🔸 How it can be used to test ML models (e.g. minimal changes needed to trigger misclassification) 🔸 The Art of the Optimal: A Pythonic Approach to Complex Decision-Making 📍 April 14 · 16:30 📍 Platinum (2nd Floor) If you're building decision-making systems in Python, this is worth a look. More details 👉 https://lnkd.in/dyifGdVi #PyConDE #PyData #Optimization #GAMSPy #GAMS #Python
To view or add a comment, sign in
-
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development