🚀 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.
Reversing Letters in a String with Java Solution
More Relevant Posts
-
🚀 Day 76: Numerically Balanced Brute Force – Java Edition Today’s challenge was deceptively simple yet oddly satisfying: 🔢 Find the next numerically balanced number greater than a given integer. A number is numerically balanced if every digit d appears exactly d times. Examples: 22 → two 2s ✅ 1333 → one 1, three 3s ✅ 122 → one 1, two 2s ❌ (2 appears only once) I went full brute-force in Java, and it worked like a charm: java public int nextBeautifulNumber(int n) { for (int i = n + 1; i <= 1224444; i++) { if (isBalanced(i)) return i; } return -1; } private boolean isBalanced(int num) { int[] count = new int[10]; int temp = num; while (temp > 0) { count[temp % 10]++; temp /= 10; } for (int i = 0; i < 10; i++) { if (count[i] != 0 && count[i] != i) return false; } return true; } 🧠 Clean logic, no fancy tricks. Just a solid loop and a digit frequency check. 📌 Lesson: Sometimes brute force is enough—if you know your bounds and keep it clean. Let me know if you’ve tackled this one differently or optimized it further. #100DaysOfCode #Java #LeetCode #ProblemSolving #NumericallyBalanced #CodingJourney #Day76
To view or add a comment, sign in
-
-
💻 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 17 📘 Problem Statement: Given two strings — haystack and needle, return the index of the first occurrence of needle in haystack. If needle is not found, return -1. 🧩 Example: Input: haystack = "sadbutsad", needle = "sad" Output: 0 Explanation: The substring "sad" appears at index 0 and 6. The first occurrence is at index 0. 🧠 Approach (Detailed Explanation): To solve this problem efficiently, I used Java’s built-in string method indexOf(). Here’s how it works step-by-step: 1. The indexOf() method in Java scans the haystack string from left to right and looks for the first occurrence of the substring needle. 2. If needle is found, it returns the starting index of that substring. 3. If the substring does not exist in haystack, it returns -1. 4. This method internally uses an optimized string matching algorithm, so it performs well even for larger inputs. ⏱️ Time Complexity: O(n * m) (in the worst case, where n = haystack length and m = needle length) 💾 Space Complexity: O(1)
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 30 of #100DaysOfCode – LeetCode Problem #88: Merge Sorted Array 🧩 Problem: You’re given two sorted arrays, nums1 and nums2, and need to merge them into a single sorted array — in-place inside nums1. The catch? You can’t return a new array, and nums1 already contains extra space for nums2. 💡 Approach: To avoid overwriting elements in nums1, we use a three-pointer approach: Start from the end of both arrays. Compare the elements and place the larger one at the back (nums1[pMerge]). Move pointers accordingly until all elements are merged. 💻 Java Code: class Solution { public void merge(int[] nums1, int m, int[] nums2, int n) { int p1 = m - 1, p2 = n - 1, pMerge = m + n - 1; while (p2 >= 0) { if (p1 >= 0 && nums1[p1] > nums2[p2]) { nums1[pMerge--] = nums1[p1--]; } else { nums1[pMerge--] = nums2[p2--]; } } } } ⏱️ Complexity: Time: O(m + n) Space: O(1) ✅ Result: Accepted (Runtime: 0 ms) A simple yet elegant example of solving array problems in-place using smart pointer manipulation!
To view or add a comment, sign in
-
🕒 𝗧𝘄𝗼 𝗠𝗶𝗻𝘂𝘁𝗲 𝗣𝗿𝗲𝗽 — 𝗟𝗮𝗺𝗯𝗱𝗮𝘀 & 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝗮𝗹 𝗜𝗻𝘁𝗲𝗿𝗳𝗮𝗰𝗲𝘀 (𝗝𝗮𝘃𝗮) Let’s clear this once and for all 👇 ✨ 𝗪𝗵𝗮𝘁’𝘀 𝘁𝗵𝗲 𝗿𝗲𝗮𝗹 𝗿𝗲𝗹𝗮𝘁𝗶𝗼𝗻 𝗯𝗲𝘁𝘄𝗲𝗲𝗻 𝗟𝗮𝗺𝗯𝗱𝗮 & 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝗮𝗹 𝗜𝗻𝘁𝗲𝗿𝗳𝗮𝗰𝗲? A Lambda Expression (→) in Java is nothing but a short-hand implementation of a Functional Interface — an interface having exactly one abstract method. 👉 The Lambda provides the implementation for that single method, removing the boilerplate of anonymous inner classes. 💭 𝗕𝗲𝗳𝗼𝗿𝗲 𝗝𝗮𝘃𝗮 𝟴 — 𝘄𝗲𝗿𝗲 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝗮𝗹 𝗜𝗻𝘁𝗲𝗿𝗳𝗮𝗰𝗲𝘀 𝗲𝘃𝗲𝗻 𝘂𝘀𝗲𝗳𝘂𝗹? Absolutely ✅ They existed long before Lambdas — think of Runnable, Callable, or Comparator. 👉 We used them via anonymous inner classes to pass behavior. 👉 Java 8 simply brought syntactic elegance + functional style. 🚫 𝗖𝗮𝗻 𝘄𝗲 𝘂𝘀𝗲 𝗟𝗮𝗺𝗯𝗱𝗮𝘀 𝘄𝗶𝘁𝗵𝗼𝘂𝘁 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝗮𝗹 𝗜𝗻𝘁𝗲𝗿𝗳𝗮𝗰𝗲𝘀? No 🙅♂️ Lambdas must target a Functional Interface. They can’t exist independently — the compiler converts them into an instance of that interface behind the scenes. 🧩 𝗜𝗻 𝘀𝗵𝗼𝗿𝘁: 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝗮𝗹 𝗜𝗻𝘁𝗲𝗿𝗳𝗮𝗰𝗲 → 𝗗𝗲𝗳𝗶𝗻𝗶𝘁𝗶𝗼𝗻 𝗟𝗮𝗺𝗯𝗱𝗮 𝗘𝘅𝗽𝗿𝗲𝘀𝘀𝗶𝗼𝗻 → 𝗜𝗺𝗽𝗹𝗲𝗺𝗲𝗻𝘁𝗮𝘁𝗶𝗼𝗻 Together, they brought 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝗮𝗹 𝗣𝗿𝗼𝗴𝗿𝗮𝗺𝗺𝗶𝗻𝗴 flavor to Java 🚀 💡 𝗙𝗼𝗹𝗹𝗼𝘄-𝘂𝗽 𝗾𝘂𝗲𝘀𝘁𝗶𝗼𝗻𝘀 𝘁𝗼 𝗿𝗲𝗳𝗹𝗲𝗰𝘁 𝗼𝗻: • Why is @FunctionalInterface annotation optional but recommended? • Can a Functional Interface have default or static methods? • What happens if a second abstract method is added accidentally? • How does type inference work with Lambdas? • Difference between Anonymous Class vs Lambda in memory and scope? • How are Lambdas implemented internally (invokedynamic)? Follow Paras Gupta, and do share with others. Happy Learning ❣️ Try to engage with answers or your experience to the relevant questions too. #Java #FunctionalProgramming #LambdaExpressions #JavaInterviewPrep #CodeWisdom #2MinPrep
To view or add a comment, sign in
-
💭 Ever wondered why your Java string operations feel slow sometimes? String vs StringBuilder vs StringBuffer — same syntax, different game. 1️⃣ STRING – Immutable & Simple Once created → it can’t be changed. Every modification creates a new object. Example: String s = "Java"; s = s + " Rocks!"; 👉 Two objects created — one discarded. ✅ Best for fixed text (like constants, messages, config values) ⚠️ Avoid in loops or repeated concatenations — it’s memory heavy 🔍 Why immutable? Thread-safe Used in String Pool for performance Prevents accidental modification 2️⃣ STRINGBUILDER – Mutable & Fast Edits the same object instead of creating new ones. Perfect for building large strings efficiently. Example: StringBuilder sb = new StringBuilder("Hello"); sb.append(" World"); ✅ Fast & memory-efficient ✅ Ideal for loops and dynamic string operations ⚠️ Not thread-safe — avoid in multi-threaded code 3️⃣ STRINGBUFFER – Mutable & Thread-Safe Same as StringBuilder but synchronized. That means only one thread can modify it at a time. Example: StringBuffer sb = new StringBuffer("Sync"); sb.append(" Safe"); ✅ Safe for multi-threaded applications ⚠️ Slower than StringBuilder due to synchronization
To view or add a comment, sign in
-
☕ Day 7 – Java 2025: Smart, Stable, and Still the Future 💡 🔹 Topic: ASCII Value in Java 🧩 What is ASCII Value? ASCII stands for American Standard Code for Information Interchange. It is a numerical representation of characters — where every letter, number, or symbol is assigned a specific numeric value between 0 and 127. For example, 'A' → 65, 'a' → 97, '0' → 48. --- ⚙️ How We Can Use ASCII Values in Java In Java, each character (char) has an internal ASCII code. You can easily get this value by type casting a character to an integer. This helps programmers perform character comparisons, sorting, encryption, and pattern logic. --- 🎯 Purpose of ASCII Values 1️⃣ Character Comparison: To check which character comes first or is greater based on ASCII order. Example: 'A' < 'a' because 65 < 97. 2️⃣ Encoding & Data Transmission: When sending text over systems or networks, ASCII ensures characters are universally understood. 3️⃣ Sorting and Logic Building: Used in string sorting algorithms or validation logic (e.g., checking if a character is uppercase, lowercase, or a number). 4️⃣ Mathematical Operations on Characters: You can perform arithmetic operations like converting uppercase to lowercase using ASCII difference. --- 💻 Simple Example char ch = 'A'; int ascii = (int) ch; // Type casting char to int System.out.println("ASCII value of " + ch + " is: " + ascii); Output: ASCII value of A is: 65 --- 🧠 Extra Insight 'A' to 'Z' → 65 to 90 'a' to 'z' → 97 to 122 '0' to '9' → 48 to 57 ASCII makes Java programs language-neutral and machine-readable for text processing tasks. --- ✨ #Day7OfJava #Java2025 #LearnJava #ASCIICode #JavaBasics #JavaCharacters #JavaForBeginners #CodeWithSneha #ProgrammingConcepts #100DaysOfJava #TechLearning #DeveloperJourney
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
-
-
9 JAVA CLEAN CODE TIPS 👇 -- Meaningful Names: Name variables and functions to reveal their purpose, not just their value. -- One Function, One Responsibility: Functions should do one thing. -- Avoid Magic Numbers: Replace hard-coded values with named constants to give them meaning. -- Use Descriptive Booleans: Boolean names should state a condition, not just its value. -- Keep Code DRY: Duplicate code means duplicate bugs. Try to reuse logic where it makes sense. -- Avoid Deep Nesting: Flatten your code flow to improve clarity and reduce cognitive load. -- Comment Why, Not What: Explain the intention behind your code, not the obvious mechanics. -- Limit Function Arguments: Too many parameters confuse. Group related data into objects. -- Code Should Be Self-Explanatory: Well-written code needs fewer comments because it reads like a story. Comment which other clean code principles would you add to this list? ✍️ Follow our Telegram channel for more - https://lnkd.in/dw6T6eYd #systemdesign #interviewtips #coding #networking #tech #microservices #architecture #data #tips #softwareengineering #api #skills #java #cleancode
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