Today I solved LeetCode 77 – Combinations using a backtracking approach. The problem asks us to generate all possible combinations of k numbers chosen from 1 to n. Instead of brute force, I used recursion with pruning to reduce unnecessary calls and improve efficiency. Key idea: Build combinations step by step Backtrack when the size reaches k Prune branches where remaining elements are insufficient Here is my Java solution: class Solution { List<List<Integer>> sol = new ArrayList<>(); public List<List<Integer>> combine(int n, int k) { generate(1, n, k, new ArrayList<>()); return sol; } public void generate(int i, int n, int k, List<Integer> sub) { if (k == 0) { sol.add(new ArrayList<>(sub)); return; } for (int j = i; j <= n - k + 1; j++) { sub.add(j); generate(j + 1, n, k - 1, sub); sub.remove(sub.size() - 1); } } } Time Complexity: O(C(n, k)) Space Complexity: O(k) This problem strengthened my understanding of recursion, pruning, and combinatorial generation. Always open to feedback and discussions. #LeetCode #Java #Backtracking #ProblemSolving #CodingJourney
LeetCode 77 - Combinations Solution with Backtracking in Java
More Relevant Posts
-
Day 42 - LeetCode Journey 🚀 Solved LeetCode 944: Delete Columns to Make Sorted in Java ✅ Today’s challenge was all about looking at data from a different perspective—literally! Instead of the usual row-by-row string processing, I had to shift my focus to vertical column-wise traversal. The Problem: Given an array of strings, imagine them stacked to form a grid. The goal is to identify and "delete" any columns that are not sorted lexicographically. The Approach: Grid Traversal: Used nested loops where the outer loop iterates through columns and the inner loop iterates through rows. Lexicographical Check: For each column, I compared characters at index row and row + 1. Optimization: As soon as a single out-of-order pair is found in a column, the break keyword ensures we stop checking that column and move to the next, keeping the solution efficient. Key Takeaways: Column-Major Order: Reinforced how to swap the standard matrix[i][j] traversal to focus on vertical data. String Manipulation: Continued practicing charAt() for precise character comparisons within a string array. Problem Decomposition: Breaking down a visual grid into simple loop logic is a crucial skill for more complex matrix problems. Whether it's pattern matching or grid manipulation, every problem is a new tool in the kit. Consistency is doing its work! 💪 #LeetCode #DSA #Java #Strings #Algorithms #ProblemSolving #CodingPractice #InterviewPreparation #Consistency #DailyCoding
To view or add a comment, sign in
-
-
🚀 𝗔𝗿𝗿𝗮𝘆𝗟𝗶𝘀𝘁 𝘃𝘀 𝗟𝗶𝗻𝗸𝗲𝗱𝗟𝗶𝘀𝘁 — 𝗪𝗵𝗶𝗰𝗵 𝗢𝗻𝗲 𝗦𝗵𝗼𝘂𝗹𝗱 𝗪𝗲 𝗨𝘀𝗲? While revising the Java Collection Framework, I realized something important. We often use ArrayList by default. But do we really understand when to use LinkedList instead? Both implement the List interface, but internally they are completely different. 🔹 𝗔𝗿𝗿𝗮𝘆𝗟𝗶𝘀𝘁 ArrayList is backed by a dynamic array. That means: • Accessing elements using index is very fast • But inserting or deleting in the middle requires shifting elements So it works best when: ✔ We mostly read data ✔ Random access is frequent 🔹 𝗟𝗶𝗻𝗸𝗲𝗱𝗟𝗶𝘀𝘁 LinkedList is backed by a doubly linked list. That means: • Insertion and deletion are faster • Accessing elements by index is slower So it works best when: ✔ We frequently add/remove elements ✔ We modify data often 𝗦𝗶𝗺𝗽𝗹𝗲 𝗖𝗼𝗱𝗲 𝗘𝘅𝗮𝗺𝗽𝗹𝗲 ->List<Integer> list1 = new ArrayList<>(); ->List<Integer> list2 = new LinkedList<>(); Same interface. Different internal working. Different performance behavior. 💡 𝗪𝗵𝗮𝘁 𝗜 𝗟𝗲𝗮𝗿𝗻𝗲𝗱 Choosing the right data structure is not about syntax. It’s about understanding the use case. The more I revise Collections, the more I realize that fundamentals matter more than memorizing methods. #Java #CollectionFramework #ArrayList #LinkedList #Programming #DSA #LearningJourney
To view or add a comment, sign in
-
-
𝐓𝐡𝐢𝐬 𝐜𝐨𝐝𝐞 𝐬𝐧𝐢𝐩𝐩𝐞𝐭 𝐢𝐬 𝐞𝐧𝐨𝐮𝐠𝐡 𝐭𝐨 𝐜𝐨𝐧𝐟𝐮𝐬𝐞 𝐬𝐨𝐦𝐞𝐨𝐧𝐞 𝐰𝐢𝐭𝐡 𝐉𝐚𝐯𝐚. 😁 Let me introduce you to the concept of wrapper classes and autoboxing first. 𝐖𝐑𝐀𝐏𝐏𝐄𝐑 𝐂𝐋𝐀𝐒𝐒𝐄𝐒: These are classes used to wrap primitive values so we can treat them like objects. This is essential for the Collection framework (like ArrayList), which only works with objects. 𝐀𝐔𝐓𝐎𝐁𝐎𝐗𝐈𝐍𝐆: The process of converting primitive values to wrapper objects is implicit. We don't need the new keyword. Now let's discuss the code: 𝐂𝐎𝐃𝐄 1: 𝘪𝘯𝘵 𝘢 = 100; 𝘪𝘯𝘵 𝘣 = 100; These are primitive values. For primitives, the == operator compares the actual values. Since both are 100, the output is 𝐭𝐫𝐮𝐞. 𝐂𝐎𝐃𝐄 2: Integer wrapper classes have an Integer Cache. By default, Java caches all Integer objects in the range of -128 to 127. 𝘐𝘯𝘵𝘦𝘨𝘦𝘳 𝘱 = 100; 𝘐𝘯𝘵𝘦𝘨𝘦𝘳 𝘲 = 100; Since 100 is in the cache, Java points both variables to the same object memory location. The output is 𝐭𝐫𝐮𝐞. 𝐂𝐎𝐃𝐄 3: 𝘐𝘯𝘵𝘦𝘨𝘦𝘳 𝘺 = 128; 𝘐𝘯𝘵𝘦𝘨𝘦𝘳 𝘻 = 128; Because 128 is outside the cache range, Java creates two distinct objects in memory. Since == compares memory references for objects, the output is 𝐟𝐚𝐥𝐬𝐞. ~Anuprash Gautam 🍵 𝘒𝘦𝘦𝘱 𝘭𝘦𝘢𝘳𝘯𝘪𝘯𝘨 𝘢𝘯𝘥 𝘣𝘳𝘦𝘸𝘪𝘯𝘨 𝘤𝘰𝘧𝘧𝘦𝘦.😊 #Java #programming #autoboxing #oops
To view or add a comment, sign in
-
-
Stop writing 50 lines of code for a simple Data Object! 🛑 Still creating traditional POJOs with endless getters, setters, hashCode(), and toString()? You’re making your codebase heavy for no reason. Enter Java Records (The game changer since Java 14/16) ⚡ The Problem: Earlier, if you wanted a simple User object, you had to write a massive block of code. It was hard to read and even harder to maintain. The Solution: With Records, you define the state, and Java takes care of the rest. Check this out: 👇 // Traditional Way (The Boring Way 😴) public class User { private final Long id; private final String name; public User(Long id, String name) { this.id = id; this.name = name; } // + Getters, hashCode, equals, toString... (40+ lines!) } // The Modern Way (The Pro Way 😎) public record User(Long id, String name) {} Why you should switch TODAY: ✅ Immutability: Fields are final by default. ✅ Conciseness: One line replaces an entire file. ✅ Readability: Focus on the "What" instead of the "How". ✅ Built-in Methods: No more manual equals() or toString() bugs. If you are still using Lombok’s @Data or @Value, give Records a try—they are native, lightweight, and super clean. Are you already using Records in your production code? Or do you prefer the classic Class approach?Let's settle this in the comments! 👇 #Java #BackendDevelopment #CleanCode #Java17 #SoftwareEngineering #CodingTips #Programming #TechCommunity
To view or add a comment, sign in
-
-
Headline: Back to Basics: Visualizing the "Stack" vs. "Heap" in Java 🧠📝 "Why did my original array change when I only modified the copy?" If you’ve ever debugged a "ghost" issue where data seemed to change on its own, you’ve likely run into the difference between Primitive Types and Reference Types. Sometimes, the best way to really cement these concepts is to close the IDE and draw it out on paper. I sketched this diagram to visualize exactly what happens under the hood in memory: 1️⃣ The Stack (Primitives) When you assign int num2 = num1, Java creates a distinct copy in the Stack. They are independent neighbors. Changing num2 leaves num1 untouched. 2️⃣ The Heap (References) Arrays are objects. When you do int B[] = A, you aren't copying the data; you are copying the reference (the address). As shown in my sketch, both A and B point to the exact same memory block in the Heap. The Result: If you change B[3], you are changing A[3] too. Mastering this flow—knowing when you are passing a value vs. sharing a reference—is day one stuff, but it remains crucial for writing bug-free code at any level. Who else finds that drawing out the Call Stack and Heap makes complex logic much easier to digest? 👇 #Java #SoftwareEngineering #DataStructures #CodingLife #MemoryManagement #LearningToCode
To view or add a comment, sign in
-
-
Stop writing boilerplate. Let the compiler do the heavy lifting. In modern Java, you can replace a verbose data class with a single line: public record Car(String name) {} Behind the scenes, Java automatically generates: ✅ Private final fields (Immutability by default). ✅ Canonical constructor (State initialization). ✅ Accessor methods (e.g., car.name()). ✅ equals() and hashCode() (Value-based equality). ✅ toString() (Readable output). // What the JVM actually sees: public final class Car extends java.lang.Record { privatefinal String name; public Car(String name) { this.name = name; } public String name() { returnthis.name; } @Overridepublic boolean equals(Object o) { ... } @Overridepublic int hashCode() { ... } @Overridepublic String toString() { ... } } The Result? Cleaner code, fewer bugs, and zero "boilerplate fatigue." Are you still using traditional POJOs, or have you switched to Records? 👇 #Java #CleanCode #SoftwareEngineering #ProgrammingTips #ModernJava
To view or add a comment, sign in
-
🚀 LeetCode Problem Solved: 454. 4Sum II Today I solved 4Sum II (Medium) on LeetCode using an optimized approach with HashMap in Java. 🔹 Problem Summary: Given four integer arrays nums1, nums2, nums3, and nums4, count the number of tuples (i, j, k, l) such that: nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0 🔹 Approach Used: Instead of using brute force (O(n⁴)), I optimized it to O(n²) using a HashMap: 1️⃣ Store all possible sums of nums1[i] + nums2[j] in a HashMap with frequency. 2️⃣ For each pair from nums3[k] + nums4[l], check if -(sum) exists in the map. 3️⃣ Add the frequency to the count. 💡 This reduces time complexity from O(n⁴) → O(n²), which is a huge improvement for large inputs. 🔹 Key Concepts Practiced: ✔ HashMap ✔ Frequency counting ✔ Time complexity optimization ✔ Thinking in terms of pair sums Consistent DSA practice is helping me improve my problem-solving patterns and optimization mindset. 💪 #LeetCode #DSA #Java #ProblemSolving #CodingJourney #SoftwareEngineering #100DaysOfCode
To view or add a comment, sign in
-
-
🔹 Problem 1: Second Smallest Element in an Array 📌 Input: Integer n (size of array), Array of n elements 📌 Output: Second smallest element in the array 🧠 Algorithm Steps: 1. Read the array elements. 2. Assume first element as first_min and second element as second_min. 3. If first_min is greater than second_min, swap them. 4. Traverse the array from index 2. 5. If current element < first_min → second_min = first_min and first_min = current element. 6. Else if current element > first_min and < second_min → update second_min. 7. If both minimum values are equal, print "No second smallest element", otherwise print second_min. 💡 Example: Input: [5, 2, 8, 1, 3] Output: 2 🔹 Problem 2: First Non-Repeating Character in a String 📌 Input: String s 📌 Output: First character that appears only once 🧠 Algorithm Steps: 1. Read the string. 2. Traverse each character. 3. For each character, count its frequency using another loop. 4. If count == 1, print that character and stop. 5. If no such character found, print -1. 💡 Example: Input: "swiss" Output: w 🔹 Problem 3: Hashad Number 📌 Input: Integer n 📌 Output: Check whether the number is Hashad or not 🧠 Algorithm Steps: 1. Store original number. 2. Find sum of digits using loop. 3. Check if original number % sum == 0. 4. If true, print "Hashad Number". 5. Otherwise, print "Not Hashad Number". 💡 Example: Input: 18 Output: Hashad Number Consistent practice of these problems is helping me improve my logical thinking, loop handling, and core Java fundamentals. 🚀 #Java #CodingPractice #ProblemSolving #CoreJava #LearningJourney
To view or add a comment, sign in
-
-
𝐉𝐚𝐯𝐚 𝐢𝐬 𝐚𝐥𝐰𝐚𝐲𝐬 𝐏𝐚𝐬𝐬-𝐛𝐲-𝐕𝐚𝐥𝐮𝐞. 𝐒𝐨 𝐰𝐡𝐲 𝐝𝐢𝐝 𝐦𝐲 𝐚𝐫𝐫𝐚𝐲 𝐜𝐡𝐚𝐧𝐠𝐞? 🤔 I wrote a simple program to test how Java handles method arguments. [1] Declared an array 𝐚𝐫𝐫 in 𝐦𝐚𝐢𝐧. [2] Passed it to a 𝐜𝐡𝐚𝐧𝐠𝐞(𝐢𝐧𝐭[] 𝐧𝐮𝐦𝐬) method. [3] Modified 𝐧𝐮𝐦𝐬[𝟎] AND 𝐧𝐮𝐦𝐬[𝟏] inside the method. [4] The original 𝐚𝐫𝐫 was updated. 𝐓𝐡𝐞 𝐄𝐧𝐠𝐢𝐧𝐞𝐞𝐫𝐢𝐧𝐠 𝐄𝐱𝐩𝐥𝐚𝐧𝐚𝐭𝐢𝐨𝐧: Java is strictly Pass-by-Value. When I passed 𝐚𝐫𝐫, I didn't pass the object itself. I passed a copy of the reference variable. [A] Both the original 𝐚𝐫𝐫 and the method parameter 𝐧𝐮𝐦𝐬 hold the same memory address (pointing to the same array object in the Heap). [B] So, when 𝐧𝐮𝐦𝐬 modifies the data, it modifies the shared object. Understanding Stack (references) vs. Heap (objects) is crucial for avoiding bugs. #Java #MemoryManagement #SoftwareEngineering #CodingInterviews #LearningInPublic #BackendDevelopment #DataStructures #Coding #WeMakeDevs #100DaysOfCode #IntelliJ
To view or add a comment, sign in
-
-
Loops work. But they don’t always express intent clearly. That’s where 𝗦𝘁𝗿𝗲𝗮𝗺𝘀 𝗔𝗣𝗜 changed Java. Instead of telling the system how to iterate, you describe what you want. Example: List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); names.stream() .filter(name -> name.startsWith("A")) .map(String::toUpperCase) .forEach(System.out::println); This reads like a pipeline: • Take a collection • Filter it • Transform it • Consume it No explicit loop. No temporary variables. No manual indexing. Streams encourage: • Functional-style thinking • Declarative code • Cleaner data transformation They also introduce: • Lambda expressions • Method references • Lazy evaluation Today was about: • Understanding 𝘀𝘁𝗿𝗲𝗮𝗺() • Difference between intermediate and terminal operations • Writing expressive and readable data pipelines Modern Java isn’t about writing more code. It’s about writing clearer code. #Java #Streams #FunctionalProgramming #CleanCode #SoftwareEngineering #LearningInPublic
To view or add a comment, sign in
-
Explore related topics
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
Nice work, Kee it up 👍