💻 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
Exploring Java Strings and StringBuilder in DSA Day 13
More Relevant Posts
-
🔍 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
To view or add a comment, sign in
-
-
Day 90 of #100DaysOfCode Solved Squares of a Sorted Array in Java 🔠 Approach The task was to take an array of integers sorted in non-decreasing order, square each number, and then return the result array also sorted in non-decreasing order. Brute-Force Method The solution implemented here is a straightforward two-step brute-force approach: Squaring: I iterated through the input array nums and replaced each element with its square (i.e., nums[i] * nums[i]). This handles both positive and negative numbers correctly. Sorting: After squaring all elements, I used Java's built-in Arrays.sort(nums) method to sort the entire array. While correct, this approach has a time complexity dominated by the sorting step, which is O(NlogN), where N is the number of elements. The runtime of 10 ms shows that a more efficient, two-pointer approach (which can solve this in O(N) time) is generally preferred for optimal performance. #Java #100DaysOfCode #LeetCode #CodingChallenge #Algorithms #Array #Sorting #ProblemSolving
To view or add a comment, sign in
-
-
Day 39 — Ones and Zeroes (0–1 Knapsack Variation) Problem: 474. Ones and Zeroes Difficulty: Medium Language: Java Status: Solved Problem Summary: Given an array of binary strings strs and two integers m and n, find the maximum subset size such that the total number of '0's ≤ m and total '1's ≤ n. Key Concept: This is a 2D 0–1 Knapsack problem, where: Each string represents an item with two “weights”: count of '0's and '1's. We must maximize the number of strings (the “value”) within the constraints of available m and n. Algorithm Steps: Count zeros and ones for each string. Iterate backwards (to avoid overwriting previous states). Update dp[i][j] = max(dp[i][j], dp[i - zeros][j - ones] + 1) for all valid i, j. Time Complexity: O(len(strs) * m * n) Space Complexity: O(m * n) Learning Takeaway: This problem strengthens understanding of multidimensional dynamic programming. The backward iteration pattern is crucial in 0–1 Knapsack-style DP to prevent reuse of the same item. #Day39 #100DaysOfCode #LeetCode #DynamicProgramming #Knapsack #DP #Java #Algorithms #CodingChallenge #ProblemSolving #DSA
To view or add a comment, sign in
-
-
🚀 Day 39 of #100DaysOfCode – LeetCode Problem #917: Reverse Only Letters 💡 Problem Summary: Given a string s, reverse only the English letters while keeping all non-letter characters in their original positions. 📘 Examples: Input: s = "ab-cd" Output: "dc-ba" Input: s = "a-bC-dEf-ghIj" Output: "j-Ih-gfE-dCba" Input: s = "Test1ng-Leet=code-Q!" Output: "Qedo1ct-eeLg=ntse-T!" 🧠 Approach: Use two pointers: one starting from the beginning and one from the end. Move both pointers until they point to letters. Swap the letters and move inward. Skip over non-letter characters. 💻 Java Solution: class Solution { public String reverseOnlyLetters(String s) { char[] res = s.toCharArray(); int left = 0, right = res.length - 1; while (left < right) { if (!Character.isLetter(res[left])) { left++; } else if (!Character.isLetter(res[right])) { right--; } else { char temp = res[left]; res[left] = res[right]; res[right] = temp; left++; right--; } } return new String(res); } } ⚙️ Complexity: Time: O(n) Space: O(n) ✅ Result: Accepted (Runtime: 0 ms) 🎯 Key Takeaway: This problem highlights precision and attention to detail — even simple string manipulations can teach valuable lessons about pointer logic and conditional handling.
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
-
-
Today I worked on the problem "Convert Sorted List to Binary Search Tree" in Java — a perfect blend of Linked List and Tree logic! 🌳 🔍 Key Concepts Covered: Finding the middle element of a Linked List using the slow & fast pointer approach Recursively constructing a height-balanced BST Strengthening understanding of Divide and Conquer strategies This problem really sharpened my thinking around recursive structures and pointer management — small yet powerful steps toward writing more efficient and elegant Java code. 💻✨ 💬 What’s your favorite data structure to work with — Linked Lists or Trees? #LeetCode #Java #DataStructures #Algorithms #CodingJourney #LearningEveryday #ProblemSolving #SoftwareEngineering
To view or add a comment, sign in
-
-
🔢 Today I worked on a classic matrix problem in Java — Diagonal Sum. The goal was simple: Calculate the sum of both the primary and secondary diagonals of a square matrix. Initially, I used a nested loop approach with O(n²) complexity. But then I optimized it to a clean O(n) solution by directly accessing diagonal indexes. While optimizing, I made an interesting mistake: ❌ I wrote if (i != matrix[i][matrix.length - 1 - i]) Here I accidentally compared an index with an element value. ✔ Correct approach: if (i != matrix.length - 1 - i) This ensures the center element in odd-sized matrices isn’t counted twice. 🧠 Key Learning: Indexes and values may look similar, but mixing them can break logic silently. Optimization is not just about speed — it’s about accuracy. #Java #leetcode #Coding #DSA #ProblemSolving #LearningInPublic #SoftwareEngineering
To view or add a comment, sign in
-
-
Day 85 of #100DaysOfCode Solved Range Sum Query - Immutable (NumArray) in Java ➕ Approach Today's problem was a classic that demonstrates the power of pre-computation: finding the sum of a range in an array many times. The optimal solution is the Prefix Sum technique. Pre-computation: In the constructor, I built a prefixSum array where prefixSum[i] holds the sum of all elements from index 0 up to index $i-1$ in the original array. This takes $O(N)$ time. $O(1)$ Query: The magic happens in the sumRange(left, right) method. The sum of any range $[left, right]$ is found instantly by calculating prefixSum[right + 1] - prefixSum[left]. The cost of a single $O(N)$ setup is outweighed by the ability to perform every subsequent query in $O(1)$ time! #Java #100DaysOfCode #LeetCode #CodingChallenge #Algorithms #Arrays #PrefixSum #Optimization #ProblemSolving
To view or add a comment, sign in
-
-
🔥 #100DaysOfDSA — Day 29/100 Topic: Binary Search in Java ⚡ 💡 What I Did Today: Today, I implemented one of the most powerful and efficient searching algorithms — Binary Search 🔍 Instead of checking every element one by one like Linear Search, Binary Search smartly divides the array in half each time — reducing the time complexity drastically! 🧠 Logic Used: Works only on sorted arrays ✅ Find the mid index: mid = (start + end) / 2 If key == numbers[mid] → found the element 🎯 If key > numbers[mid] → search in right half Else → search in left half Continue until the element is found or the range is empty 📊 Example: Input → {4, 5, 6, 10, 18, 61, 122} Key → 61 ✅ Output → index for key is: 5 ⚙️ Time Complexity: O(log n) — super fast compared to O(n) of Linear Search 💨 ✨ Takeaway: Binary Search is a fundamental algorithm that teaches the power of divide and conquer. Mastering this concept builds the foundation for more advanced topics like search trees, sorting, and algorithm optimization 🚀 #100DaysOfCode #Day29 #Java #DSA #BinarySearch #ProblemSolving #CodingJourney #LearnInPublic #DeveloperLife #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