Day 8 of 365 days of code: Qn 1) Remove the duplicates from the array. Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Consider the number of unique elements in nums to be k. After removing duplicates, return the number of unique elements k. The first k elements of nums should contain the unique numbers in sorted order. The remaining elements beyond index k - 1 can be ignored. use two pointer technique. let L=1 starting from position r=1, we overwrite the number at L if nums[r-1]!=nums[r]. this process is like copy pasting the unique elements on the left side of the array, in a sorted order. #365daysOfCode #NeetCode #leetcode #DSA #python #LeetCode #ProblemSolving #Algorithms #365dayschallenge
Remove Duplicates from Sorted Array in Python
More Relevant Posts
-
#week -2 Topic : Arrays - DSA Array : An array is used to store a collection of elements under a single variable ,instead of storing the data indifferent variables which saves the memory. let us discuss some array operations : 1) #max and min num in an array def find_max_min(arr): if not arr: return none max_val=arr[0] min_val=arr[0] for num in arr: if num>max_val: max_val=num if num<min_val: min_val=num return max_val, min_val arr=[1, 6,7,0,4] print(find_max_min(arr) ) 2) #sum of elements arr = [1, 2, 3, 4, 5] total = 0 for num in arr: total += num print(total) def reverse_array(arr): start = 0 end = len(arr) - 1 while start < end: arr[start], arr[end] = arr[end], arr[start] start += 1 end -= 1 return arr arr = [1, 2, 3, 4, 5] print(reverse_array(arr)) #DSA #python #arrays #learning
To view or add a comment, sign in
-
This problem is all about finding the largest common "gap" between any two fences in both the horizontal and vertical directions. Since a square requires equal side lengths, the goal is to find the largest distance that exists in both sets of fence combinations. THE STRATEGY 📐 Define All Boundaries: Start by adding the outer boundaries of the field to your fence lists. For horizontal fences, include 1 and m. For vertical fences, include 1 and n. 📏 Calculate All Possible Gaps: Generate every possible distance between any two horizontal fences. Store these in a set for quick lookup. Do the same for all possible distances between vertical fences. 🤝 Find the Intersection: Look for distances that appear in both the horizontal gaps set and the vertical gaps set. These represent potential side lengths for a square field. 🏆 Pick the Maximum: Identify the largest value from this intersection. If no common distance exists, the answer is -1. 🔢 Handle Large Numbers: Square the largest side length found and apply the modulo 10^9 + 7 to the result. COMPLEXITY ⚡ Time: O(H^2 + V^2) - Where H and V are the number of horizontal and vertical fences. We compare all pairs within each group. 💾 Space: O(H^2) - To store the set of all possible horizontal gap lengths for comparison. Full Implementation: https://htmlify.me/r/h0x0 #LeetCode #DSA #Python
To view or add a comment, sign in
-
-
Day 35 of 365 days of code So far, so good Qn 1) Online stock span approach: decreasing monotonic stack Inside the constructor(__init__ block): initialize an empty stack we are going to use the stack to store the prices and the span Inside the function block(next): 1) set span=1 2) while the stack is not empty and the price at the top of the stack is less than the price: i) span+=stack.pop() 3) push the price and the span, as a tuple inside the stack. 4) return span. #365daysOfCode #NeetCode #leetcode #DSA #python #LeetCode #ProblemSolving #Algorithms #365dayschallenge
To view or add a comment, sign in
-
-
Python with DSA — Day 33 What I worked on: Prime checks: moved from naive divisibility to the √n optimization and the 6k±1 rule to cut unnecessary iterations. Time complexity intuition: compared O(n) vs O(√n) for primality tests; saw how early exits change best/worst cases. Clean loops & edge cases: handled n <= 1, negative inputs, and printed primes from 1–100 with a tight loop. Key snippet (conceptual): Idea: Only test divisors up to √n; if none divide, the number is prime. #Day33 #PythonWithDSA #DataStructures #DSAJourney #ProblemSolving #PythonProgramming #SoftwareEngineer
To view or add a comment, sign in
-
-
Day 75 of #100DaysOfLeetCode Today’s challenge focused on matrix optimization using prefix sums — a great example of turning brute force into an efficient solution. 🟨 Maximum Side Length of a Square with Sum ≤ Threshold (LeetCode 1292) We need to find the largest square submatrix such that: ✔ The sum of all its elements ≤ threshold ✔ Return the maximum possible side length 🧠 My Approach Built a 2D prefix sum array Used it to calculate any submatrix sum in O(1) Checked square sizes efficiently to find the maximum valid one This problem shows how preprocessing can drastically reduce complexity. 💡 What I Learned Prefix sums are extremely powerful for grid problems Brute force becomes practical after optimization Many matrix problems reduce to smart range queries 📊 Complexity Analysis Time Complexity: O(m × n × min(m, n)) Space Complexity: O(m × n) ✅ Day 75 Summary Simple idea. Strong technique. Clean implementation. Progressing steadily toward 100. 🚀 On to Day 76. #100DaysOfLeetCode #Day75 #LeetCode #PrefixSum #Matrix #DynamicProgramming #DSA #ProblemSolving #Python #CodingJourney #AdityaCodes
To view or add a comment, sign in
-
-
Day 76 of #100DaysOfLeetCode Today’s challenge focused on matrix optimization using prefix sums — a great example of turning brute force into an efficient solution. 🟨 Maximum Side Length of a Square with Sum ≤ Threshold (LeetCode 1292) We need to find the largest square submatrix such that: ✔ The sum of all its elements ≤ threshold ✔ Return the maximum possible side length 🧠 My Approach Built a 2D prefix sum array Used it to calculate any submatrix sum in O(1) Checked square sizes efficiently to find the maximum valid one This problem shows how preprocessing can drastically reduce complexity. 💡 What I Learned Prefix sums are extremely powerful for grid problems Brute force becomes practical after optimization Many matrix problems reduce to smart range queries 📊 Complexity Analysis Time Complexity: O(m × n × min(m, n)) Space Complexity: O(m × n) ✅ Day 76 Summary Simple idea. Strong technique. Clean implementation. Progressing steadily toward 100. 🚀 On to Day 77. #100DaysOfLeetCode #Day75 #LeetCode #PrefixSum #Matrix #DynamicProgramming #DSA #ProblemSolving #Python #CodingJourney #AdityaCodes
To view or add a comment, sign in
-
-
🚀 Day 77 of #100DaysOfCode — Find the Second Largest Digit Hey everyone! 👋 Today's challenge is "Second Largest Digit in a String" — a great problem for practicing digit extraction, comparison logic, and edge-case handling. We’ll search through a mixed string of letters and numbers to find the second largest digit, or return -1 if it doesn’t exist. 👨💻 What l practiced today: ✅ String Traversal: Looping through each character and identifying digits. ✅ Digit Comparison: Keeping track of the largest and second-largest digits efficiently. ✅ Edge Cases: Handling cases with no digits, only one digit, or duplicate digits. 📌 Today’s Task: ✔ Given an alphanumeric string s. ✔ Return the second largest numerical digit that appears in s. ✔ Return -1 if it doesn’t exist. Example: Input: s = "dfa12321afd" Digits: [1, 2, 3] Second largest: 2 → Output: 2 🧠 Key Insight: You can solve this by scanning the string once, tracking the largest and second largest digits. Remember to skip duplicates and handle cases where all digits are the same. #100DaysOfCode #Day77 #Python #LeetCode #DSA #StringManipulation #DigitExtraction #EdgeCases #AlgorithmPractice #LogicBuilding
To view or add a comment, sign in
-
-
🚀 #DAY74 LeetCode Problem #1200 – Minimum Absolute Difference 🧩 Problem Summary Given a list of distinct integers, the goal is to find all element pairs whose absolute difference is the minimum possible and return them in sorted order. 🧠 How It Works First, sort the array to bring close values together Scan once to compute the minimum difference between adjacent elements Scan again to collect all pairs that match this minimum difference This approach leverages the fact that in a sorted array, the smallest difference must occur between neighboring elements. 📘 What I Learned ✔ Why sorting simplifies difference-based problems ✔ How breaking the task into two passes improves clarity ✔ Turning mathematical observations into efficient logic ✔ Writing clean and readable solutions even when performance isn’t maxed 📊 Performance ⏱ Runtime: 95 ms 💾 Memory: 21.57 MB ✅ 38 / 38 testcases passed 📌 Small optimizations, big clarity — consistency is the real win. #LeetCode #DSA #Algorithms #ProblemSolving #Python #CodingPractice #DataStructures #TechJourney #100DaysOfDSA #LearningByDoing #Consistency #InterviewPrep #CompetitiveProgramming
To view or add a comment, sign in
-
-
𝗗𝗮𝘆 𝟰𝟬/𝟳𝟱 | 𝗟𝗲𝗲𝘁𝗖𝗼𝗱𝗲 𝟳𝟱 𝗣𝗿𝗼𝗯𝗹𝗲𝗺: 872. Leaf-Similar Trees 𝗗𝗶𝗳𝗳𝗶𝗰𝘂𝗹𝘁𝘆: Easy 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 𝗦𝘂𝗺𝗺𝗮𝗿𝘆: Two binary trees are leaf-similar if the sequence of their leaf node values (from left to right) is identical. We must return true only if both trees produce the same leaf sequence. 𝗠𝘆 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵: Use DFS traversal to collect leaf nodes from both trees into two lists. During traversal, whenever a node has no children, add its value to the list. Finally, compare the two lists to check if the leaf sequences matched. 𝗖𝗼𝗺𝗽𝗹𝗲𝘅𝗶𝘁𝘆 𝗔𝗻𝗮𝗹𝘆𝘀𝗶𝘀: • Time Complexity: O(n + m) • Space Complexity: O(n + m) (n and m are the number of nodes in each tree) 𝗞𝗲𝘆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆: DFS traversal is a simple and reliable way to extract structural patterns like leaf sequences from trees. 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝗟𝗶𝗻𝗸: https://lnkd.in/g38aqnfp #Day40of75 #LeetCode75 #DSA #Python #Java #MachineLearning #DataScience #ML #DataAnalyst #LearningInPublic #TechJourney #LeetCode
To view or add a comment, sign in
-
-
🚀 Day 9/30 | LeetCode Problem: Binary Search (704) Problem: Given a sorted array of integers nums and a target, return the index if the target exists. If not, return -1. 🧠 Approach: Binary Search Since the array is already sorted, we can apply Binary Search: Use two pointers: l (left) and r (right) Find the middle element Compare target with nums[mid] Reduce the search space by half each time This makes the solution very efficient. ⏱️ Complexity Time: O(log n) Space: O(1) 🧾 Python Code class Solution(object): def search(self, nums, target): l = 0 r = len(nums) - 1 while l <= r: mid = (l + r) // 2 if target == nums[mid]: return mid elif target < nums[mid]: r = mid - 1 else: l = mid + 1 return -1 ✅ Result Accepted ✅ Runtime: 0 ms (Beats 100%) Memory efficient 🎯 Key Learning Binary Search is a foundational algorithm used in: Search problems Optimization problems Interview questions Mastering it is essential for every developer. 🔖 Hashtags #LeetCode #30DaysOfLeetCode #Day9 #BinarySearch #Python #DSA #ProblemSolving #CodingJourney #SoftwareEngineering
To view or add a comment, sign in
-
More from this author
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