Problem: 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. Idea: Given that array is sorted in increasing order and to main the relative order of array, All we need to do is that take two pointers adjacent pointer at start where compare left to right using second pointer with first pointer and check if elements at first and second aren't same, then increase first pointer and replace element of 1st pointer with second pointer and return first +1; class Main { public static void main(String[] args) { System.out.println("Try programiz.pro"); int[] nums={0,0,1,2,3,3,3,3,5,6}; int unqiueCount = removeDuplicates(nums); System.out.println("Total unqiue element after removing duplicates are: "+ unqiueCount); } static int removeDuplicates(int[] nums) { int first = 0; for(int second = 1; second<nums.length; second ++){ if(nums[first]!=nums[second]){ first++; nums[first]=nums[second]; } } return first+1; } } #java8 #corejava #programming #practice #java #code #leetcodeproblem #problemsolving
Remove Duplicates from Sorted Array
More Relevant Posts
-
Day 95/100 – #100DaysOfCode 🚀 | #Java #HashMap #Randomization ✅ Problem Solved: Random Flip Matrix (LeetCode 519) 🧩 Problem Summary: You are given a binary matrix initialized with all 0s. Each call to flip() should randomly return the position of a 0 and change it to 1. No position should be flipped more than once until reset() is called. 💡 Approach Used: ✔ Used HashMap + Randomization to simulate shuffling ✔ Treat the matrix as a flattened 1D array Steps: Map each index to its actual value using a HashMap Randomly pick an index from the remaining unflipped range Swap it with the last available index Decrease the available range On reset(), clear the map and restore the range ⚙ Time Complexity: O(1) per flip() 📦 Space Complexity: O(K) (where K = number of flipped cells) ✨ Takeaway: This problem is a great example of achieving uniform randomness without storing the entire matrix — smart indexing beats brute force. #Java #LeetCode #HashMap #Randomization #100DaysOfCode #CodingChallenge
To view or add a comment, sign in
-
-
Why did Java just skip my input? (The sc.nextLine() Trap) I was building a simple CLI tool today and hit a weird bug. I asked the user for their Age, then their Name. But as soon as I typed the age and hit Enter, the program finished. 𝐈𝐭 𝐝𝐢𝐝𝐧'𝐭 𝐞𝐯𝐞𝐧 𝐰𝐚𝐢𝐭 𝐟𝐨𝐫 𝐦𝐞 𝐭𝐨 𝐭𝐲𝐩𝐞 𝐦𝐲 𝐧𝐚𝐦𝐞! 𝐓𝐡𝐞 𝐌𝐲𝐬𝐭𝐞𝐫𝐲: I was using sc.nextInt() followed by sc.nextLine(). ▶️sc is the Scanner class object. 𝐓𝐡𝐞 𝐒𝐜𝐢𝐞𝐧𝐜𝐞: When you type 25 and hit Enter, nextInt() only reads the 25. It leaves the "𝐄𝐧𝐭𝐞𝐫" (𝐭𝐡𝐞 \𝐧 𝐧𝐞𝐰𝐥𝐢𝐧𝐞 𝐜𝐡𝐚𝐫𝐚𝐜𝐭𝐞𝐫) sitting there in the buffer. When the code hits the next nextLine(), it sees that leftover "Enter" and thinks: "Oh, the user just pressed Enter without typing anything!" So it returns an empty string and moves on. 𝐓𝐡𝐞 𝐅𝐢𝐱: We have to "consume" the ghost! I learned you need to call an extra 𝐬𝐜.𝐧𝐞𝐱𝐭𝐋𝐢𝐧𝐞() just to clear that leftover newline before taking the actual input. 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠 𝐢𝐧 𝐏𝐮𝐛𝐥𝐢𝐜: Coming from C++, I'm used to cin.ignore(), but seeing it happen in Java was a great reminder of how input buffers work under the hood. Have you ever been haunted by the nextLine() ghost? How did you first solve it? #Java #CodingBeginner #SoftwareEngineering #Scanner #LearningInPublic
To view or add a comment, sign in
-
-
📌 DSA Series — Day 2 - Problem 2 | Arrays Problem: Rotate Array (Rotate Right by k Steps) 🔹 Problem Understanding: Given an array, rotate it to the right by k steps, where k can be greater than the array length. 🔹 Approach: Reduce k using modulo (k % n) to avoid unnecessary rotations. Store the last k elements in a temporary array. Shift the remaining elements to the right by k positions. Copy the stored elements back to the front. 🔹 Why this works: Right rotation essentially moves the last k elements to the front while preserving the order of the rest. 🔹 Time Complexity: O(n) 🔹 Space Complexity: O(k) 🔹 Java Implementation: class Solution { public void rotate(int[] nums, int k) { if (nums == null || nums.length == 0) return; k %= nums.length; if (k == 0) return; // Createing a Temp array int n = nums.length; int[] temp = new int[k]; // Copy last k elements for (int i = 0; i < k; i++) { temp[i] = nums[n - k + i]; } // Shift remaining elements for (int i = n - 1; i >= k; i--) { nums[i] = nums[i - k]; } // Restore temp for (int i = 0; i < k; i++) { nums[i] = temp[i]; } } } 🔹 Key Insight: Using modulo prevents redundant rotations when k is larger than the array size. 📈 Continuing my daily DSA problem-solving series. #DSA #Arrays #Java #ProblemSolving #StriversA2Z #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 21 of my DSA Journey (LeetCode + Java) Today’s practice focused on Array Manipulation + Counting Frequency problems. All three questions looked simple at first, but each required a deeper thought process to get the most optimized solution. ✅ Problems Solved Today LC 66 – Plus One LC 88 – Merge Sorted Array LC 1189 – Maximum Number of Balloons 🧠 My Experience Solving These: 🔸 66. Plus One This problem was trickier than I expected. Initially, I solved it in a non-optimized way. Then I realized the key insight: Traverse from the end If digit < 9, just increment and return If digit is 9 → make it 0 and continue If all digits are 9 → create new array with leading 1 Once I understood this, I solved it in one single loop—clean and efficient. 🔸 88. Merge Sorted Array My first approach used two loops and sorting, but it was: Extra time Not optimal Then I optimized it by using three pointers: i at the end of arr1 j at the end of arr2 k at the final position Compare & place larger element → move pointers. Finally append remaining elements from arr2. This method was fully optimized (O(n)) without any extra space. 🔸 1189. Maximum Number of Balloons This one was fun! I used a HashMap to count frequency of characters. The tricky part was: How to divide counts correctly for repeated characters like 'l' and 'o' After several dry runs, the logic became clear: Count freq of each char in text Count required freq for word “balloon” Divide actual/required → minimum of all divisions = answer A clean and optimal solution. 📌 Key Takeaway Today Even simple array problems can become tricky if we miss the pattern. Today I reinforced: ✔ Think from the end for digit problems ✔ Use three pointers for merging arrays ✔ Frequency-based problems → always check min(actual/required) ✔ Dry run is your best friend Step-by-step progress every day is building my confidence and logical thinking. 💪 On to Day 22! 🚀 #DSA #LeetCode #Java #Arrays #HashMap #ProblemSolving #CodingJourney #Consistency #LearningDaily
To view or add a comment, sign in
-
🧠Array Memory Model & Random Access Mechanism ✅ An array is an object and is always stored in heap memory. 🔑 Contiguous Memory Allocation JVM looks for a continuous block of memory Size required = (size of data type × number of elements) Example: int[] arr = new int[5]; int = 4 bytes Total = 5 × 4 = 20 bytes JVM allocates 20 continuous bytes in heap 3️⃣ Address vs Index vs Value (VERY IMPORTANT) They are three different things 👇 Address ----- Actual memory location (hidden from Java developer) IndexPosition ----- number (0, 1, 2, …) Value ----- Data stored at that position 📌 You never see addresses in Java 📌 You only work with indexes 4️⃣ How does JVM access arr[i] so fast? This is the key concept you’re describing 👇 🔑 Direct Address Calculation (Random Access) Internally JVM does something like: address = baseAddress + (index × sizeOfDataType) Example: arr[3] JVM knows base address of arr Knows int = 4 bytes Calculates: base + (3 × 4) 👉 No loop, no search, no traversal 👉 Direct jump to memory location 📌 This is why arrays are very fast for reading 5️⃣ Why arrays are fast for READ but slow for WRITE? ✅ Fast Read Because of random access JVM jumps directly to the address ❌ Slow Insert / Delete Size is fixed To insert in middle: Shift elements Adjust values Cannot resize memory 📌 This is why arrays are rigid 6️⃣ Can we insert into an array? ❌ No. Arrays are fixed size Once created: new int[5]; Size = 5 forever JVM cannot resize that memory block 👉 Any “insertion” means: Create a new array Copy old values Add new value 📌 This is expensive 🧠 Java Memory — Objects & References (Quick Clarity) 👉 Objects (including arrays) are stored in the Heap 🧱 👉 Reference variables are stored in the Stack 📍 👉 The reference variable stores the base address of the object, ✔️ not the value ✔️ not index 0 ✔️ but the starting address of the array object itself 👉 Inside memory, each address holds both location + actual value 📦 🔖 Frontlines EduTech (FLM) #Java #JVM #HeapMemory #StackMemory #ProgrammingConcepts #JavaInternals
To view or add a comment, sign in
-
-
𝐖𝐡𝐲 𝐉𝐚𝐯𝐚 𝐝𝐨𝐞𝐬𝐧'𝐭 "𝐝𝐨𝐮𝐛𝐥𝐞-𝐬𝐩𝐞𝐧𝐝" 𝐲𝐨𝐮𝐫 𝐦𝐞𝐦𝐨𝐫𝐲 🧠 In my last post, we talked about String Immutability. Today, let’s look under the hood at the 𝐒𝐭𝐫𝐢𝐧𝐠 𝐂𝐨𝐧𝐬𝐭𝐚𝐧𝐭 𝐏𝐨𝐨𝐥 (SCP). When you create a String in Java, the JVM is very stingy with your RAM. It has two ways to handle things: 1. 𝐓𝐡𝐞 "𝐍𝐞𝐰" 𝐖𝐚𝐲 (𝐄𝐱𝐩𝐥𝐢𝐜𝐢𝐭 𝐎𝐛𝐣𝐞𝐜𝐭 𝐂𝐫𝐞𝐚𝐭𝐢𝐨𝐧) 👉 String name = new String("Arpit"); This creates a brand new object in the Heap Memory, even if "Arpit" already exists elsewhere. It’s like buying a new book when there’s already a copy on the shelf. 2. 𝐓𝐡𝐞 𝐋𝐢𝐭𝐞𝐫𝐚𝐥 𝐖𝐚𝐲 (𝐓𝐡𝐞 𝐒𝐦𝐚𝐫𝐭 𝐖𝐚𝐲) 👉 String platform = "LinkedIn"; This tells the JVM: "Check the 𝐒𝐭𝐫𝐢𝐧𝐠 𝐂𝐨𝐧𝐬𝐭𝐚𝐧𝐭 𝐏𝐨𝐨𝐥 first." If "LinkedIn" is already there, your variable just points to it. If it’s not, it creates it. Result: 100 variables can point to the same "LinkedIn" string, saving massive amounts of memory. 𝐓𝐡𝐞 "𝐈𝐧𝐭𝐞𝐫𝐧" 𝐏𝐫𝐨-𝐓𝐢𝐩 💡 What if you created a string with new but want to move it into the pool to save space? Enter the .intern() method. As you can see in the 𝐝𝐢𝐚𝐠𝐫𝐚𝐦 (Credit: Scaler): - str1 and str3 point to the same "Java" in the pool. - str4 sits alone in the Heap. - str6 uses .intern() to jump from the Heap into the Pool! 𝐖𝐚𝐢𝐭, 𝐰𝐡𝐚𝐭 𝐚𝐛𝐨𝐮𝐭 𝐜𝐨𝐧𝐜𝐚𝐭𝐞𝐧𝐚𝐭𝐢𝐨𝐧? When you add two strings, Java creates a new string in the pool rather than changing the old one. This keeps your data safe and predictable. Did you know about this before? Let me know in the comments! 👇💭 #java #SoftwareEngineering #jvm #LearningInPublic
To view or add a comment, sign in
-
-
Problem 2: Binary Tree Paths Level: Easy–Medium Platform: LeetCode 257 Return all root-to-leaf paths as strings like: Copy code "1->2->5" "1->3" 🔹 Java Code import java.util.*; class Solution { public List<String> binaryTreePaths(TreeNode root) { List<String> result = new ArrayList<>(); if (root == null) return result; dfs(root, "", result); return result; } private void dfs(TreeNode node, String path, List<String> result) { if (node == null) return; // add current node to path path = path + node.val; // leaf -> store path if (node.left == null && node.right == null) { result.add(path); return; } // continue path with "->" path = path + "->"; dfs(node.left, path, result); dfs(node.right, path, result); } } 🔹 Explanation Build path as a string while traversing When leaf reached → store full path No backtracking needed because we use new string each recursion call Time: O(n × path-length) Space: O(h) recursion #DSA #DataStructuresAndAlgorithms #Coding #Programmer #LeetCode #CodeEveryday #JavaDSA #CodingPractice #ProblemSolving #CP #CompetitiveProgramming #DailyCoding #TechJourney #CodingCommunity #DeveloperLife #100DaysOfCode #CodeWithMe #LearnToCode #GeekForGeeks #CodingMotivation
To view or add a comment, sign in
-
🔴 OutOfMemoryError vs 🔵 StackOverflowError 🟦 OutOfMemoryError → Happens when JVM cannot allocate memory for new objects. Happens in Heap Memory Caused by too many objects / memory leak Common with large collections or heavy data java.lang.OutOfMemoryError: Java heap space 🟦 StackOverflowError → Happens due to infinite or deep recursive method calls. Happens in Stack Memory Caused by infinite or deep recursion Each method call consumes stack space java.lang.StackOverflowError JVM MEMORY --- ┌─────────────────────┐ │ HEAP │ ← Objects │ (new, arrays, │ │ collections) │ │ ❌ FULL → OOM │ └─────────────────────┘ ┌─────────────────────┐ │ STACK │ ← Method calls │ (call frames, │ │ local variables) │ │ ❌ DEEP → SOE │ └─────────────────────┘ #Java #JVM #BackendDeveloper #JavaDeveloper #Programming
To view or add a comment, sign in
-
#200DaysOfCode – Day 103 Generate Parentheses Problem :- Generate Parentheses Task :- Given n pairs of parentheses, generate all combinations of well-formed parentheses. Example: Input: n = 3 Output: ["((()))","(()())","(())()","()(())","()()()"] My Approach: Used Backtracking to build the string step by step. Tracked the count of open and close brackets. Added '(' only when open < n. Added ')' only when close < open. Stored the result when the string length reached 2 * n. Time Complexity: Exponential (Catalan-based) Space Complexity: O(n) (recursion stack) Key Takeaway: Instead of generating all possibilities and checking validity later, applying constraints during recursion leads to clean, efficient, and elegant solutions. #takeUforward #200DaysOfCode #Java #LeetCode #ProblemSolving #Backtracking #Recursion #DSA #CodingJourney #CodeNewbie #CleanCode
To view or add a comment, sign in
-
-
Day 20/60: Binary Search Trees — The Reality Check 🔍 Today was about implementing Binary Search Trees (BST) in Java. While the concept is simple, the implementation exposed some critical gaps in my recursive logic. The Hurdles & Mistakes: The Return Value Trap: I struggled with returning the correct node during recursion. In Java, if you don't link the returned node back to the parent (root.left = insert(...)), the new node is lost and the tree never grows. Missing Base Cases: I missed a null check on an empty tree, leading to an immediate NullPointerException. In backend development, unhandled nulls are production killers. Duplicate Handling: I didn't initially plan for existing values. Deciding how to handle duplicates is crucial for defining consistent system behavior. The Lessons: Visualize First: I stopped coding and started drawing. If you can’t trace the recursion on paper, you can’t debug it in the IDE. Defensive Coding: I’m learning to write the "Exit Condition" first. Knowing when to stop is more important than knowing how to proceed. State Management: BSTs taught me that how we structure data at the point of entry determines the speed of every future query. Status: ✅ Fixed: Recursive Insertion and Search logic. 🛠️ Working on: Visualizing the call stack deeper. 🎯 Goal: Day 21 – Mastering the three cases of Node Deletion. Refining the logic, one error at a time. 🚀 #JavaDeveloper #Backend #60DaysOfDSA #BinarySearchTree #CodingHurdles #SoftwareEngineering #LearningInPublic
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