🚀 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
Java solution for numerically balanced numbers challenge
More Relevant Posts
-
Day 91 of #100DaysOfCode Solved Base 7 in Java 🔢 Approach The challenge was to convert a given integer (num) to its base 7 string representation. Conversion Method The core of the solution lies in the standard algorithm for base conversion: repeated division and remainder collection. Handle Zero and Negatives: If the input num is 0, the result is immediately "0". I determined if the number is negative and stored this in a boolean flag, then proceeded with the absolute value of the number (num = Math.abs(num)) for the conversion logic. Conversion Loop: I used a while loop that continues as long as num > 0. In each iteration: The remainder when num is divided by 7 (num % 7) gives the next digit in base 7. This digit is appended to a StringBuilder. num is then updated by integer division by 7 (num /= 7). Final Result: Since the remainders are collected in reverse order, I called sb.reverse(). If the original number was negative, I prepended a hyphen (-) to the reversed string. Finally, I returned the result as a string. This simple and efficient implementation had a very fast runtime, beating 77.39% of submissions. #Java #100DaysOfCode #LeetCode #CodingChallenge #Algorithms #BaseConversion #ProblemSolving
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
-
💭 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 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 7 — The Multithreading Mystery That Breaks Developer Logic 🧩 Every Java developer says: “I know how threads work.” But when two threads share the same object… even pros get confused about what actually happens 👇 class Printer implements Runnable { int count = 0; @Override public void run() { for (int i = 0; i < 3; i++) { System.out.println(Thread.currentThread().getName() + " → " + count++); } } public static void main(String[] args) { Printer printer = new Printer(); Thread t1 = new Thread(printer, "Thread-A"); Thread t2 = new Thread(printer, "Thread-B"); t1.start(); t2.start(); } } 💭 Question: What could be the possible output? 1️⃣ Each thread prints 0 1 2 independently 2️⃣ The count value increases continuously (shared between threads) 3️⃣ Compile-time error 4️⃣ Unpredictable output 💬 Drop your guess in the comments 👇 Most devs think they know the answer — until they realize what “shared object” actually means in Java threading 😵💫 Can you explain why it happens? 🧠 #Java #Multithreading #Concurrency #CodingChallenge #JavaDeveloper #InterviewQuestion #Day7Challenges #SpringBoot
To view or add a comment, sign in
-
Primitives vs Wrappers in Java: A Practical Balance for Performance and API Design 💡 In Java, choosing between primitive types (int, boolean, long) and their wrapper counterparts (Integer, Boolean, Long) isn’t just a speed race—it shapes how you model nullability, API contracts, and data flows. 🚀 Primitives win on performance and memory: fewer objects, no nulls, and straightforward arithmetic. They’re the default for local variables and tight loops. 🧭 Wrappers unlock object‑oriented conveniences: nullability, easy use in generics, and compatibility with reflection or frameworks. But boxing/unboxing and higher memory usage can sneak into hot paths. Key takeaways: - Use primitives in performance‑sensitive code and internal math. - Use wrappers in DTOs, API surfaces, or data stores where nulls or optional values matter. - Prefer primitive streams (IntStream, LongStream) to avoid boxing in data pipelines. - If you need to express absence with primitives, consider OptionalInt/OptionalLong rather than nulls. - When working with large, memory‑sensitive collections, consider primitive‑specific collections from third‑party libraries. - Be mindful of NPEs when a wrapper value is null. Bottom line: balance is design‑driven, not dogmatic. Align your choice with API guarantees and performance budgets. What’s your take? Have you faced a scenario where the primitive vs wrapper choice changed performance or design outcomes? What specific suggestions would you add to improve this post (e.g., with a short code snippet)? #Java #JavaPerformance #PrimitivesVsWrappers #SoftwareEngineering #Programming
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
-
💻 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
-
When I was practicing Java algorithms yesterday, I ran into the good ol’ .equals() method, one of the more well-known methods. I knew I needed to use it when comparing instances of wrapper classes like Integer and Character, but I wanted to understand why. While digging, I came across something really interesting about Integer. If an Integer value is in the range -128 to 127 (that’s -(2^(8-1)) to 2^(8-1)-1), Java actually caches the value. Thanks to this caching, the == operator can sometimes work instead of .equals(). Another really cool thing Java does is autobox and unbox values automatically. For example: Integer x = 5; // autoboxed into the wrapper class Integer y = Integer.valueOf(5); // manual equivalent int z = x; // unboxed back into primitive int This lets you move seamlessly between primitives and wrapper objects, which is especially handy when working with collections. You definitely wouldn’t want to rely on the caching in production code, but the JVM does it as a small efficiency boost because these numbers are so commonly used. Makes me wonder what else the JVM is quietly doing under the hood.
To view or add a comment, sign in
-
-
☕ Understanding final, finally, and finalize() in Java These three keywords may sound similar, but they serve completely different purposes in Java! Let’s clear the confusion 👇 🔹 final (Keyword) Used for declaring constants, preventing inheritance, or stopping method overriding. final variable → value can’t be changed final method → can’t be overridden final class → can’t be inherited 👉 Example: final int MAX = 100; 🔹 finally (Block) Used in exception handling to execute important code whether or not an exception occurs. Perfect for closing files, releasing resources, or cleaning up memory. 👉 Example: try { int a = 10 / 0; } catch (Exception e) { System.out.println("Error"); } finally { System.out.println("This will always execute"); } 🔹 finalize() (Method) It’s a method called by the Garbage Collector before an object is destroyed. Used to perform cleanup operations before object removal (though it’s deprecated in newer Java versions). 👉 Example: protected void finalize() { System.out.println("Object destroyed"); } --- 💡 Quick Summary: Keyword Used For Level final Restriction (variable, method, class) Compile-time finally Cleanup code block Runtime finalize() Object cleanup (GC) Runtime --- #Java #Programming #FinalFinallyFinalize #JavaDeveloper #ExceptionHandling #TechLearning #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