Day 21/100: String Compression & Memory 📦 Today I tackled String Compression in Java (e.g., "aaabb" -> "a3b2"). The Goal: Compress a string by counting repeated characters. Example:"aaabbc" becomes "a3b2c1". If the compressed string isn't actually shorter, return the original. Key Learning: StringBuilder vs. String In Java, strings are immutable. If you add to a string in a loop, Java creates a new object every single time. To fix this, I used **StringBuilder**, which is much faster and memory-efficient for building long strings. The Strategy: 1️⃣ Iterate through the string once. 2️⃣ Keep a running count of identical consecutive characters. 3️⃣ Append the character and count to the builder. Simple logic, big performance difference. 🚀 #100DaysOfCode #Java #DSA #Strings #Optimization #Unit2 #CodingJourney #LearnInPublic
Java String Compression with StringBuilder
More Relevant Posts
-
🚀 Day 52/100 Today’s problem was based on String Manipulation — reversing the first k characters of a string. 🧠 What I learned: - How to efficiently manipulate strings - Using "StringBuilder" for reversal in Java - Writing clean and optimized code 💡 Approach: Reversed the first k characters and appended the remaining string. ⚡ Key Insight: Even simple problems help strengthen fundamentals, which are crucial for solving complex problems later. 👨💻 Code (Java): class Solution { public String reversePrefix(String s, int k) { String first = new StringBuilder(s.substring(0, k)).reverse().toString(); String rest = s.substring(k); return first + rest; } } 📈 Consistency is the key — showing up every day matters more than perfection. #Day52 #CodingChallenge #Java #DSA #LearningJourney #Consistency #100DaysOfCode
To view or add a comment, sign in
-
-
Something small… but it changed how I think about Java performance. We often assume `substring()` is cheap. Just a slice of the original string… right? That was true **once**. 👉 In older Java versions, `substring()` shared the same internal char array. Fast… but risky — a tiny substring could keep a huge string alive in memory. 👉 In modern Java, things changed. `substring()` now creates a **new String with its own memory**. Same value ❌ Same reference ❌ Safer memory ✅ And this is where the real learning hit me: **Understanding behavior > memorizing APIs** Because in a real system: * Frequent substring operations = more objects * More objects = more GC pressure * More GC = performance impact So the question is not: “Do I know substring?” But: “Do I know what it costs at runtime?” That shift — from syntax to system thinking — is where growth actually starts. #Java #BackendEngineering #Performance #JVM #LearningJourney
To view or add a comment, sign in
-
Leetcode Practice - 16. 3Sum Closest The problem is solved using JAVA Given an integer array nums of length n and an integer target, find three integers at distinct indices in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution. Example 1: Input: nums = [-1,2,1,-4], target = 1 Output: 2 Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). Example 2: Input: nums = [0,0,0], target = 1 Output: 0 Explanation: The sum that is closest to the target is 0. (0 + 0 + 0 = 0). Constraints: 3 <= nums.length <= 500 -1000 <= nums[i] <= 1000 -104 <= target <= 104 #LeetCode #Java #CodingPractice #ProblemSolving #DSA #Array #DeveloperJourney #TechLearning
To view or add a comment, sign in
-
-
🚀 **Day 4/30 – LeetCode Java Challenge** Today’s problem pushed me to think beyond basic comparisons and focus on **pattern-based validation**. Worked on a string problem where the key insight was separating characters based on **even and odd indices**, then comparing frequency distributions instead of direct string matching. 📊 **Result:** ✔️ Accepted (752/752 test cases) ⚡ Runtime: 5 ms (Beats 93.81%) 💾 Memory: Efficient (Beats 86.60%) 💡 **What actually mattered today:** * Brute force thinking won’t scale — pattern recognition does * Breaking a problem into smaller logical groups simplifies everything * Frequency arrays can outperform more complex data structures when used correctly Let’s be real: This wasn’t a hard problem, but the approach matters. If you miss the pattern, you overcomplicate it. If you see it early, the solution becomes clean and efficient. Day 4 done. Still building consistency, still sharpening fundamentals. Archana J E Bavani k Deepika Kannan Divya Suresh Hari priya B Devipriya R Harini B Bhavya B Kezia H Vaishnavi Janaki #LeetCode #Java #DSA #ProblemSolving #Consistency #30DaysOfCode
To view or add a comment, sign in
-
-
💡 Strings in Java — Small Concept, Big Impact At first, I thought Strings were simple… But in real projects, I learned: ➡️ Strings are immutable ➡️ Memory is optimized using String Pool ➡️ Wrong usage can impact performance Example mistake I made: String result = ""; for (int i = 0; i < 1000; i++) { result += i; // ❌ creates multiple objects } ✅ Better approach: StringBuilder sb = new StringBuilder(); for (int i = 0; i < 1000; i++) { sb.append(i); } ✨ What I learned: ✔ Use StringBuilder for heavy operations ✔ Understand equals() vs == ✔ Be mindful of memory Sometimes the simplest concepts teach the biggest lessons. #Java #Strings #CleanCode #SoftwareEngineering #BackendDevelopment #LearningJourney
To view or add a comment, sign in
-
-
This confused me when I started working with exceptions public void test() throws Exception { throw new Exception("Error"); } Now see this: public static void main(String[] args) { test(); ❌ } 👉 This won’t compile! 💥 Error: Unhandled exception: Exception 👉 Why? Because test() is throwing a checked exception So Java forces you to handle it. ✅ Option 1: try { test(); } catch (Exception e) { e.printStackTrace(); } ✅ Option 2: public static void main(String[] args) throws Exception { test(); } 💡 Lesson: Checked exceptions must be handled either where they occur or where they are called. Did this confuse you earlier? 👇 #Java #CoreJava #ExceptionHandling #Programming #BackendDeveloper #Coding
To view or add a comment, sign in
-
📅 Day 10 – Strings in Java 📚 Topic: String Manipulation (Hashing) Today I solved the problem of checking whether two strings are anagrams using an efficient frequency-count approach. This helped me understand how hashing can be used to compare character distributions instead of sorting. ✔ Key Learnings: • Applied hashing using a frequency array • Improved understanding of character frequency comparison • Learned how to optimize from sorting (O(n log n)) to linear time (O(n)) Building problem-solving skills step by step and focusing on writing efficient code 🚀 #DSA #Strings #Java #ProblemSolving #LearningJourney
To view or add a comment, sign in
-
-
Day 94/100 – Consistency Journey Today’s focus: Strings in DSA + Java Multithreading Practiced string problems involving sliding window, two pointers, and pattern-based thinking. Realized how much efficiency improves when you move from brute force to optimized approaches. On the backend side, explored ExecutorService in Java — understanding how thread pools help manage multiple tasks efficiently instead of creating threads manually every time. Key takeaway: DSA builds problem-solving mindset, while backend concepts like multithreading show how things actually scale in real-world systems. Slowly connecting both worlds. Consistency > Motivation. #Day94 #100DaysOfCode #DSA #Java #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
-
-
How the JVM Works (Simple Breakdown) We compile and run Java code every day, but what actually happens inside the JVM? Here’s the flow: 1. Build (Compilation) javac converts your .java code into bytecode (.class). This bytecode is platform-independent. 2. Load The JVM loads classes only when needed using class loaders: Bootstrap → core Java classes Platform → extensions System → your application 3. Link Before execution: Verify → checks bytecode safety Prepare → allocates memory for static variables Resolve → converts references into memory addresses 4. Initialize Static variables get their values and static blocks run (only once). 5. Memory Heap & Method Area → shared Stack & PC Register → per thread Garbage Collector manages memory automatically. 6. Execute Interpreter runs bytecode JIT compiler converts frequently used code into native code 7. Run Your program runs using a mix of interpreted and compiled code, improving performance over time. Follow Ankit Sharma for more such insights.
To view or add a comment, sign in
-
-
• Why Does Java Use 2 Bytes for "char"? At first glance, this can feel confusing… =>Why does Java use 2 bytes (16 bits) for a single character, when older languages used just 1 byte? Let’s break it down : -> The Core Reason: Unicode Support Java uses the Unicode standard to represent characters. 1) Unicode is designed to support a wide range of global character sets 2) It includes scripts like Latin, Devanagari, Chinese, Arabic, and more =>To accommodate this, Java chose 16 bits (2 bytes) for "char" => What Does 2 Bytes Mean? - 1 byte = 8 bits - 2 bytes = 16 bits =>This allows representation of up to 65,536 distinct values =>Why Not 1 Byte Like C/C++? Languages like C/C++ were originally based on ASCII: • 1 byte (8 bits) → limited character range => Java, on the other hand, was designed with broader character representation in mind. • Important Insight Java uses UTF-16 encoding for "char" 1) Most commonly used characters fit within 2 bytes 2) Some characters are represented using surrogate pairs --> Conclusion Java’s choice of 2 bytes for "char" is rooted in its design around Unicode-based character representation rather than ASCII limitations. #Java #Programming #Unicode #SoftwareEngineering #BackendDevelopment #Java #CoreJava #JavaDeveloper #JVM #ProgrammingConcepts #BackendDeveloper #DevelopersOfLinkedIn #Tech #Coding
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