🔍 Problem Statement: Given an integer array sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order. 🧠 Key Idea: Since the array is already sorted, negative numbers can affect the order after squaring. To handle this efficiently, I used the two-pointer approach — one starting from the beginning and one from the end — comparing squares and filling the result array from the back. ⚙️ Time Complexity: O(n) 🗂️ Space Complexity: O(n) 💬 Code (Java): import java.util.Arrays; class Solution { public int[] sortedSquares(int[] nums) { int n = nums.length; int[] res = new int[n]; int left = 0, right = n - 1, index = n - 1; while (left <= right) { int lsq = nums[left] * nums[left]; int rsq = nums[right] * nums[right]; if (lsq > rsq) { res[index--] = lsq; left++; } else { res[index--] = rsq; right--; } } return res; } } ✨ Learning: Improved my understanding of two-pointer technique. Reinforced the importance of optimizing sorting-related problems. #Java #DSA #Coding #ProblemSolving #StriversSheet #LearningEveryday
"Sorting Squares of a Sorted Array in Java"
More Relevant Posts
-
💻 DSA – Day 13 : Strings & StringBuilder Today I explored Strings in Java, a core concept used in almost every application — from input handling to algorithms, data processing, and problem-solving. Strings look simple, but there's a lot happening under the hood. 🌈 What I learned today 🔹 ❓ What are Strings? A sequence of characters stored as an object in Java. Strings are immutable, which means once created, they cannot be changed. 🔹 ⌨️ Input & Output Took string inputs using Scanner and printed them with basic operations. 🔹 📏 String Length Used .length() to find the number of characters. 🔹 ➕ String Concatenation Joined strings using +, concat(), and StringBuilder. 🔹 🔡 charAt() Method Accessed characters using index values. 🔹 🔄 Check if a String is Palindrome Compared characters from both ends to verify if the string reads the same backwards. 🔹 🧭 Shortest Path Problem Calculated the shortest path (N/E/W/S directions) using coordinate logic. 🔹 ⚖️ String compare() Compared strings lexicographically using .compareTo(). 🔹 ✂️ substring() Function Extracted specific parts of the string. 🔹 🏆 Print Largest String Compared strings alphabetically to find the largest one. 🔹 🔒 Why Strings Are Immutable? Because they are stored in the String Pool and designed for security, caching, and thread-safety. 🧵 StringBuilder – Faster & Mutable 🔹 Unlike Strings, StringBuilder is mutable 🔹 Perfect for modifying strings repeatedly (loops, concatenation, dynamic strings) ✨ Extra Concepts Learned 🔹 🔤 Convert Letters to Uppercase Converted the first letter of each word to uppercase (title case-style logic). 🔹 📦 String Compression Implemented character frequency compression like: aaabbccc → a3b2c3 🚀 Loving the learning curve Strings are everywhere — mastering them builds a strong foundation for upcoming DSA topics. #DSA #Strings #Java #StringBuilder #CodingJourney #100DaysOfCode #LearningInPublic #ProblemSolving #Day13
To view or add a comment, sign in
-
Day 88 of #100DaysOfCode Solved Decrypt String from Alphabet to Integer Mapping in Java 🔡 Approach Today's challenge involved mapping a string of digits to lowercase English characters, where single digits '1' through '9' map to 'a' through 'i', and two digits followed by a '#' (e.g., '10#', '11#') map to 'j' through 'z'. I used an iterative approach with a while loop and an index i to traverse the input string. I checked ahead to see if a two-digit mapping existed by looking for a '#' at s.charAt(i + 2). If a '#' was found, I parsed the two-digit number (e.g., "10", "11") using s.substring(i, i + 2), converted it to an integer, and then mapped it to the correct character by adding it to the ASCII value of 'a' and subtracting one. I then advanced the index i by 3. If no '#' was found, it meant the current character s.charAt(i) was a single-digit mapping. I converted this digit to an integer and mapped it to a character similarly, then advanced the index i by 1. This approach processes the string from left to right, correctly handling the two-digit encodings first, which resulted in a quick runtime that beat 79.30% of other submissions. #Java #100DaysOfCode #LeetCode #CodingChallenge #Algorithms #StringManipulation #ProblemSolving
To view or add a comment, sign in
-
-
Day 37/100 ✅ Binary Tree Postorder Traversal Today I solved the Binary Tree Postorder Traversal problem using a simple recursive approach in Java. In postorder traversal, we visit nodes in the order Left → Right → Root. This helps in many real-world tree-based algorithms like expression tree evaluations or file system traversal. 💡 Approach: I used recursion — first visiting the left child, then the right child, and finally adding the node’s value to the result list. It’s clean, elegant, and easy to understand! ✅ Key Learning: Understanding traversal patterns (Preorder, Inorder, Postorder) is essential for mastering tree-based problems. Each pattern teaches how to process data at different stages of recursion. #LeetCode #Java #CodingJourney #DSA #BinaryTree #Recursion #PostorderTraversal #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Jump Search Implementation (Data Structures And Algorithms) This Java code demonstrates the jump search algorithm. It works by jumping ahead by a fixed step and then performing a linear search within that block. The jump size is typically the square root of the array size. Jump search is more efficient than linear search but less efficient than binary search. It's particularly useful when accessing elements is expensive (e.g., reading from a disk). #Algorithms #DataStructures #CodingInterview #ProblemSolving #professional #career #development
To view or add a comment, sign in
-
-
Day 47/100 – #100DaysOfCode 🚀 | #Java #Arrays #InPlaceAlgorithms ✅ Problem Solved: First Missing Positive (LeetCode 41) 🧩 Problem Summary: Given an unsorted array, find the smallest missing positive integer. The solution must run in O(n) time and constant extra space. 💡 Approach Used: This is not a direct sorting or hashing problem — the key is index positioning. Logic: The answer must lie within 1 to n+1. Place each positive number x at index x-1 if possible. Then scan to find the first index where nums[i] != i+1. Steps: Iterate and swap values into their correct position. Ignore values ≤0 or >n. Final scan to find the first missing positive. ⚙️ Time Complexity: O(n) 📦 Space Complexity: O(1) ✨ Takeaway: This problem teaches how index-based hashing can eliminate the need for extra space — very common in interview-style optimization problems. #Java #LeetCode #Algorithm #Array #ProblemSolving #100DaysOfCode #CodingChallenge
To view or add a comment, sign in
-
-
Day 50 / 100— DSA From Scratch (Medium) Problem Solved: Construct Binary Tree from Preorder and Inorder Traversal Task: Rebuild a binary tree using the given preorder and inorder traversal arrays. Approach Used: Used a recursive divide-and-conquer approach. The first element in the preorder array represents the root. Found the root’s position (mid) in the inorder array — everything to its left forms the left subtree, and everything to its right forms the right subtree. Used Arrays.copyOfRange() to split both arrays for recursive calls. Initially, I was stuck thinking about the algorithm — how to connect preorder and inorder logically — but once I saw how the recursion works, it became very clear. Also, I learned a new method — the copyOfRange() function in Java, which helped simplify array slicing during recursion. Complexity: Time Complexity: O(n²) — due to searching for the root index each time. Space Complexity: O(n²) — because of repeated array slicing. Reflection: This problem taught me more than just recursion — it showed how traversal patterns can reconstruct an entire tree when understood properly. Every problem like this builds not just coding skills but also clarity in algorithmic thinking. #Day50 #DSAFromScratch #BinaryTree #Preorder #Inorder #Recursion #Java #ProblemSolving #LeetCode #LearningEveryday #100DaysOfCode
To view or add a comment, sign in
-
-
💡 LeetCode 3110 – Score of a String 💡 Today, I solved LeetCode Problem #3110: Score of a String, a neat little challenge that emphasizes understanding of ASCII values and absolute differences in Java strings. 🔠✨ 🧩 Problem Overview: You’re given a string s. The score of the string is defined as the sum of the absolute differences between the ASCII values of consecutive characters. Return the total score. 👉 Example: Input → "hello" Output → 13 Explanation → |'e'-'h'| + |'l'-'e'| + |'l'-'l'| + |'o'-'l'| = 3 + 7 + 0 + 3 = 13 💡 Approach: 1️⃣ Initialize a variable sum to store the total score. 2️⃣ Traverse the string from index 1 to end. 3️⃣ For each pair of consecutive characters, find their ASCII difference using Math.abs(). 4️⃣ Add the difference to sum and return it. ⚙️ Complexity Analysis: ✅ Time Complexity: O(n) — Single traversal of the string. ✅ Space Complexity: O(1) — Constant extra space. ✨ Key Takeaways: Strengthened understanding of character encoding and ASCII values. Reinforced clean looping logic and mathematical precision in Java. A great example of how simplicity can elegantly solve a real problem. 🌱 Reflection: Even the smallest coding challenges help sharpen attention to detail — from understanding data types to leveraging built-in functions effectively. Consistency is what transforms learning into mastery. 🚀 #LeetCode #3110 #Java #StringManipulation #ASCII #ProblemSolving #DSA #CodingJourney #CleanCode #AlgorithmicThinking #ConsistencyIsKey
To view or add a comment, sign in
-
-
🚀 Day 41 of #100DaysOfCode – LeetCode Problem #1332: Remove Palindromic Subsequences 💬 Problem Summary: You’re given a string s consisting only of 'a' and 'b'. In one step, you can remove any palindromic subsequence from s. You need to find the minimum number of steps to make the string empty. 🧩 Example: Input: s = "ababa" Output: 1 Explanation: The entire string is already a palindrome, so remove it in one step. Input: s = "abb" Output: 2 Explanation: Remove "bb" → "a" → "" (2 steps) 🧠 Logic: ✅ If the string is already a palindrome → 1 step. ✅ Otherwise → remove all 'a's in one step and all 'b's in another → 2 steps. 💡 Key Insight: Since the string only contains 'a' and 'b', it will never take more than 2 moves. 💻 Java Solution: class Solution { public int removePalindromeSub(String s) { if (isPalindrome(s)) return 1; return 2; } public boolean isPalindrome(String s) { int i = 0, j = s.length() - 1; while (i < j) { if (s.charAt(i) != s.charAt(j)) return false; i++; j--; } return true; } } ⚙️ Complexity: Time: O(n) Space: O(1) ✅ Result: Accepted (Runtime: 0 ms) 💬 Takeaway: Sometimes, a problem seems complicated until you spot the pattern — here, limiting characters to 'a' and 'b' turns a potential recursion problem into a simple mathematical observation.
To view or add a comment, sign in
-
Day 38/100 – #100DaysOfCode 🚀 | #Java #LeetCode #StringParsing #Validation ✅ Problem Solved: Valid Number 🧩 Problem Summary: Given a string, determine whether it represents a valid number. This includes handling cases like: Integers Decimals Scientific notation (e / E) Sign symbols (+ / -) Trailing and leading spaces 💡 Approach Used: This is a string interpretation + state validation problem. I validated the number by checking: Only one decimal point allowed. Only one e or E, and it must split the number into valid components. Sign characters allowed only at the start or just after e/E. At least one digit must appear appropriately. Instead of using regex or parsing libraries, I implemented logical rules step-by-step to ensure strong input handling. ⚙️ Time Complexity: O(n) 📦 Space Complexity: O(1) ✨ Takeaway: Even simple inputs can require careful rule-based parsing — validating strings is more about logic than syntax. #Java #LeetCode #Strings #Parser #StateMachine #ProblemSolving #100DaysOfCode #CodingChallenge
To view or add a comment, sign in
-
-
Day 17 of #JavaWithDSAChallenge - Remove Duplicates from Sorted Array Today’s DSA problem was a classic but super-important one - removing duplicates from a sorted array in-place. This problem teaches how to think in terms of two-pointer techniques, in-place modifications, and optimizations without extra space-all of which are heavily used in interviews at top product-based companies. Problem Summary We are given a sorted integer array, and the challenge is to: Remove duplicate values Keep one copy of each element Do it in-place (no extra array allowed) Return the count of unique elements Anything beyond that index doesn’t matter. Approach Used - Two Pointer Technique Since the array is already sorted, duplicates appear next to each other. We use: Pointer j → scans all elements Pointer i → stores position where next unique number should go Whenever we find a number that is different from the previous, we copy it to nums[i] and move i forward. This ensures all unique elements accumulate at the front of the array. Java Code class Solution { public int removeDuplicates(int[] nums) { int i = 1; // pointer for unique elements for (int j = 1; j < nums.length; j++) { if (nums[j] != nums[j - 1]) { nums[i] = nums[j]; i++; } } return i; // number of unique elements } } Key Takeaways Sorted arrays make duplicate detection easy Two-pointer pattern is extremely powerful In-place operations improve space efficiency Great practice for interview questions on arrays & optimization #JavaWithDSAChallenge #Day17 #DSA #LeetCode #Java #CodingJourney #ProblemSolving #TwoPointerTechnique #WomenInTech #SoftwareEngineering #LearnToCode #CodeNewbie
To view or add a comment, sign in
-
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