🚀 Day 29 of my DSA Journey (LeetCode + Java) Today’s focus was on Prefix Sum + Hashing — a powerful combination for solving subarray problems efficiently. Once I understood how prefix sums and hash maps work together, these problems became much clearer and more optimized. ✅ Problems Solved Today: LC 523 – Continuous Subarray Sum LC 325 – Maximum Size Subarray Sum Equals k LC 974 – Subarray Sums Divisible by K 🧠 My Experience Solving These: 🔸 LC 523 – Continuous Subarray Sum This problem was tricky at first. I learned that if two prefix sums have the same remainder when divided by k, the subarray between them is divisible by k. Using a HashMap to store remainder and index helped me solve this in O(n) time. 🔸 LC 325 – Maximum Size Subarray Sum Equals k Here, the goal was to find the longest subarray with sum k. I used prefix sum + HashMap and stored the first occurrence of each sum to maximize subarray length. Simple idea, but very powerful. 🔸 LC 974 – Subarray Sums Divisible by K This problem focused on counting subarrays. Instead of storing indices, I stored frequency of remainders in a HashMap. Each repeated remainder formed valid subarrays divisible by k. 📌 Key Takeaway Today: Prefix Sum + Hashing can solve many subarray problems efficiently. ✔ Convert subarray logic into prefix sums ✔ Use HashMap to track sums or remainders ✔ Handle negative values carefully ✔ One pass → O(n) optimized solutions Every day I’m learning how to recognize patterns faster and write cleaner, optimized code. 💪 On to Day 30 🚀 #DSA #LeetCode #Java #PrefixSum #HashMap #ProblemSolving #CodingJourney #Consistency #LearningDaily
LeetCode Java Prefix Sum Hashing DSA Journey
More Relevant Posts
-
🚀 Day 2/30 – Java DSA Challenge 🔎 Problem 9: 1. Two Sum (LeetCode – Easy) Solved one of the most popular and frequently asked interview questions today 🔥 This problem introduces the power of HashMap for optimization. 🧠 Problem Statement Given an array of integers nums and an integer target, return the indices of two numbers such that they add up to the target. ✔ Each input has exactly one solution ✔ You cannot use the same element twice ✔ Return indices in any order 💡 Example Input: nums = [2,7,11,15] target = 9 Output: [0,1] Because 2 + 7 = 9 ✅ 👨💻 Approach (Optimized – Using HashMap) ✔ Create a HashMap to store number and its index ✔ For each element: Compute target - nums[i] Check if it already exists in the map ✔ If found → return indices ✔ Otherwise → store current number in map This reduces time complexity from O(n²) to O(n). ⏱ Time Complexity: O(n) – Single pass through the array 📦 Space Complexity: O(n) – For storing elements in HashMap 📌 Key Learning: Using HashMap helps optimize brute-force solutions and is a common interview pattern for array problems involving pairs. Day 2 getting stronger 💪🔥 Consistency builds mastery 🚀 #Day2 #30DaysOfCode #Java #DSA #LeetCode #HashMap #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
🍎 hashCode() vs equals() Contract ☐☐☐☐☐ (HashBuckets) In Java, every object can have two important methods from Object class: ✅ equals() Used to check logical equality (content-based comparison) You override it when you want two different objects to be treated as equal based on fields (like id, name) ✅ hashCode() Returns an int number used mainly by hash-based collections for fast searching, where to store/search the object internally (bucket/index) ✅ The Contract Between equals() and hashCode() ✅ Rule 1 (Mandatory) If two objects are equal using equals() → they must have the same hashCode() ➡️ a.equals(b) == true => a.hashCode() == b.hashCode() ✅ Rule 2 (Not Mandatory) If two objects have the same hashCode() → they may or may not be equal (this is called a Hash collision) ➡️ a.hashCode() == b.hashCode() does NOT guarantee a.equals(b) == true Hash-based collections use them in 2 steps: hashCode() → to find the correct bucket quickly ⚡ equals() → to confirm the exact match ✅ So: ✅ hashCode() = speed ✅ equals() = correctness ✅ Collections that use Hash Buckets These collections internally use hash buckets/indexing: HashMap HashSet LinkedHashMap LinkedHashSet Hashtable 📌 Difference note: HashSet stores only unique values HashMap stores key-value pairs and hashing is applied mainly on the key 🍎 Mini Fruit Market Analogy Think of hashCode() like the basket number where fruits are placed, and equals() like checking the actual fruit inside the basket to confirm it’s the same type. Same basket can have multiple fruits, but equals decides the exact match. 🔖Frontlines EduTech (FLM) #Java #CoreJava #OOP #Equals #HashCode #HashMap #HashSet #CollectionsFramework #JavaDeveloper #DSA #Programming #InterviewPrep
To view or add a comment, sign in
-
-
🚀 Day 3/30 – Java DSA Challenge 🔎 Problem 20: 205. Isomorphic Strings (LeetCode – Easy) Today’s problem focused on bidirectional mapping using HashMap 🔥 🧠 Problem Statement Two strings s and t are isomorphic if: ✔ Each character in s maps to exactly one character in t ✔ No two characters in s map to the same character in t ✔ Order must be preserved Example: "egg" → "add" ✅ "paper" → "title" ✅ "foo" → "bar" ❌ 💡 Approach Used To ensure correct mapping in both directions: ✔ Use two HashMaps map1 → s → t map2 → t → s ✔ Traverse both strings together ✔ Check consistency in both maps ✔ If conflict found → return false This ensures one-to-one mapping (bijection). ⏱ Time Complexity: O(n) 📦 Space Complexity: O(1) – At most 256 ASCII characters 📌 Key Learning Learned importance of two-way mapping Understood how to validate bijection Strengthened string + HashMap logic 20 Problems Completed 🔥 Day 3 progressing strong 💪🚀 #Day3 #30DaysOfCode #Java #DSA #LeetCode #HashMap #StringProblems #CodingJourney #Consistency
To view or add a comment, sign in
-
-
🚀 Day 1/30 – Java DSA Challenge 🔎 Problem 7: 2744. Find Maximum Number of String Pairs (LeetCode – Easy) Solved my seventh problem for Day 1 of the 30 Days DSA challenge. 🧠 Problem Statement We are given an array of distinct strings, where each string has length 2. We can form a pair (i, j) if: ✔ words[i] is equal to the reverse of words[j] ✔ 0 ≤ i < j < words.length ✔ Each string can belong to at most one pair We need to return the maximum number of pairs that can be formed. 💡 Example Input: ["cd","ac","dc","ca","zz"] Output: 2 Explanation: "cd" pairs with "dc" "ac" pairs with "ca" Maximum pairs = 2 👨💻 Approach ✔ Use nested loops to check all possible pairs ✔ For each pair, reverse one string ✔ If reversed string matches the other → increment count ✔ Return total count Since the constraints are small (≤ 50), a brute-force approach works efficiently.⏱ Time Complexity: O(n²) Because we compare every pair of strings. 📦 Space Complexity: O(1) No extra data structures used (only temporary strings). 📌 Key Learning: When constraints are small, a simple brute-force solution is often acceptable and easier to implement. Seven problems completed on Day 1 🔥💪 Building consistency one problem at a time 🚀 #Day1 #30DaysOfCode #Java #DSA #LeetCode #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
Most people know that String is immutable in Java. Very few can explain why. This question looks simple, but it reveals how deeply you understand Java. String is immutable mainly because Java uses it everywhere — in passwords, URLs, database connections, and file paths. If a String could be changed after creation, it would become a serious security risk. Another big reason is memory efficiency. Java stores Strings in a common pool, so multiple references can point to the same object. Immutability makes this sharing safe and prevents unexpected side effects. It also helps with performance. String’s hashcode is cached, which makes it reliable and fast when used as a key in HashMap. And since it can’t be modified, String is naturally thread-safe. Questions like this remind me that learning Java isn’t about memorizing answers. It’s about understanding the design decisions behind the language. Keep learning. Keep questioning. That’s how strong engineers are built. #Java #CoreJava #JavaDeveloper #SoftwareEngineering #Learning
To view or add a comment, sign in
-
While solving a competitive programming problem, I revisited an interesting concept in Java’s BigInteger class — especially the meaning of certainty in isProbablePrime(). 🔹 Problem Statement Given a number n (which can be very large), determine whether it is prime or not prime. 📌 Note: The number may contain hundreds of digits, so primitive data types (int, long) are not sufficient. 🔹 Why normal prime checking fails ❌ Traditional logic like: using for loop and finding the primenumber for (int i = 2; i <= sqrt(n); i++) does not work because: 1. int / long overflow for large inputs 2. sqrt() cannot be calculated for huge numbers 3. Time complexity becomes impractical 🔹 Correct Approach using BigInteger Java provides a built-in method:-- isProbablePrime(int certainty)--- Here, certainty means: The level of confidence that the number is prime (The probability of error is less than 1 / 2^certainty) 🔹 Java Program (Competitive-ready) import java.io.*; import java.math.BigInteger; public class Solution { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); String n = br.readLine().trim(); BigInteger number = new BigInteger(n); if (number.isProbablePrime(1)) { System.out.println("prime"); } else { System.out.println("not prime"); } } } ✔️ Handles very large numbers ✔️ Passes hidden test cases ✔️ Fast and reliable 🔹 Key Learning 💡 certainty is not the number to test It controls how confident Java should be Even certainty = 1 is sufficient for most competitive platforms 📚 Takeaway: When dealing with very large numbers, rely on BigInteger’s probabilistic algorithms instead of manual prime-checking logic. #Java #BigInteger #CompetitiveProgramming #ProblemSolving #LearningEveryDay #CodingTips
To view or add a comment, sign in
-
🚀 DSA in Java | Shortest Path Using NSEW Directions 🚀 While practicing Data Structures & Algorithms in Java, I solved a classic logic problem: 👉 Finding the shortest path after a sequence of directions (N, S, E, W). 📌 Problem Insight: Given a string consisting of directions: N (North) S (South) E (East) W (West) We track movement on a 2D plane starting from (0, 0) and calculate the shortest distance from the origin after completing the full path. 🧠 Approach Used: Maintain two variables x and y for horizontal and vertical movement Traverse the string once Update coordinates based on direction Final shortest path = |x| + |y| (Manhattan Distance) ⚙️ Complexity: Time Complexity: O(n) Space Complexity: O(1) 💡 What I learned from this problem: ✅ Translating real-world movement into code ✅ Coordinate system fundamentals ✅ Importance of absolute values in distance calculation ✅ Writing optimized and readable Java logic I’m consistently practicing DSA in Java to improve problem-solving skills and build a strong foundation for backend and system-level development. 📈 Learning Focus: Core Java DSA fundamentals Logic building Writing optimized solutions One problem at a time, getting better every day 💻🔥 #DSA #Java #ProblemSolving #LearningInPublic #CodingJourney #JavaDeveloper #DataStructures #Algorithms #100DaysOfCode #BackendDevelopment
To view or add a comment, sign in
-
-
🚀 DSA Journey – Day 4 (Java) Today I moved deeper into Functions in Java (Methods) and explored how Java handles memory and parameters internally. In Java, functions are called methods, and I understood the structure clearly: static returnType methodName(parameters) { // method body } 📘 What I learned today: 🔹 Pass by Value in Java Java is strictly pass by value. For primitive types (int, char, double, etc.) Only a copy of the value is passed. So swapping two numbers inside a method does NOT affect the original variables. For objects (arrays, strings, classes) A copy of the reference is passed. So modifying the object inside the method affects the original object. It is not pass by reference because Java does not expose raw pointers like C/C++. 🔹 Scoping & Shadowing Local variables exist only inside their block/method Class-level variables can be accessed across methods Shadowing happens when a local variable hides a class variable with the same name 🔹 Variable Arguments (Varargs) Using: datatype... v Allows passing multiple values Internally treated as an array Must always be the last parameter 🔹 Method Overloading Multiple methods with the same name but different parameters (Changing type or number of parameters) This improves readability and flexibility of code. Today’s session made me realize that understanding how methods behave internally is crucial before moving deeper into DSA. 📌 Next: Strengthening arrays and problem-solving. Step by step. Consistency over speed. #DSA #Java #LearningInPublic #Day4 #BTechStudent #AspiringSoftwareEngineer
To view or add a comment, sign in
-
Our training has officially started, and the first topic we explored was Method Overloading 🔹 Method Overloading Method Overloading is the process of creating multiple methods with the same name inside the same class. ✔ In method overloading, name clashes may happen, but Java resolves them at compile time. ✔ The Java compiler resolves overloading by checking in this order: • Method name • Number of parameters • Data type of parameters • Order of data types 📌 Real-time example: substring() method • Accepts one argument • Also accepts two arguments 🔹 Polymorphism Polymorphism means “one is to many” — a method existing in multiple forms. 📌 Real-time example: Carbon exists in multiple forms that is Carbon dioxide, Coal, Graphite, Diamond and many more ➡ Same element, different forms. 🔹 Virtual Polymorphism Virtual polymorphism is not real polymorphism, but an illusion to the user. 📌 Example: Mobile power button • User thinks one button performs both ON and OFF. In reality, there are two separate methods: • One for power ON and One for power OFF ➡ Hence, it is called virtual (not true) polymorphism 🔹 Method Overloading as Compile-Time Polymorphism ✔ Method calling and method binding happen at compile time ✔ Hence, method overloading is called: • Compile-Time Polymorphism • Early Binding 🔹 Overloading Type Promotion If an exact match is not found, Java: • Looks for the closest possible match • Checks the number of type conversions ⚠ If multiple methods have the same number of conversions, → Ambiguous method call error occurs. 📌 Key Takeaway: Even though we say “one method performs multiple tasks”, 👉 In reality, one method always performs only one task. 💡 Understanding these basics clearly makes advanced Java concepts much easier! Huge Thanks to MALLIKARJUN V VERNEKAR for the guidance. #Java #OOPsConcepts #MethodOverloading #Polymorphism #CompileTimePolymorphism #JavaLearning #ProgrammingBasics 🚀
To view or add a comment, sign in
-
-
🔷 TreeSet in Java – 📌 1. What is TreeSet? TreeSet is a class in Java that implements the NavigableSet (SortedSet) interface. It stores unique elements only and maintains them in sorted (ascending) order by default. 👉 No duplicates 👉 Automatically sorted Internally, TreeSet uses a Red-Black Tree (self-balancing binary search tree). ⚙ 2. Internal Data Structure of TreeSet When you add an element: set.add("Java"); Internally: 👉 Element is placed in a Red-Black Tree 👉 Tree keeps elements in sorted order 👉 Tree remains balanced for performance 🧠 Structure Used: • Red-Black Tree • Self-balancing BST This guarantees: ✅ Sorted data ✅ Good performance 🧱 4. Constructors of TreeSet 1️⃣ Default Constructor TreeSet<String> set = new TreeSet<>(); • Natural sorting order 2️⃣ With Comparator (custom sorting) TreeSet<String> set = new TreeSet<>(Collections.reverseOrder()); • Descending order 3️⃣ With Collection TreeSet<String> set = new TreeSet<>(list); • Removes duplicates • Sorts automatically ⭐ 5. Important Characteristics ✔ No duplicate elements ✔ Always sorted ✔ Does NOT allow null (Java 8+) ✔ Not synchronized ✔ Slower than HashSet & LinkedHashSet TAP Academy , Rohit Ravinder , Somanna M G , Sharath R , Ravi Magadum , kshitij kenganavar , Poovizhi VP , Hemanth Reddy #Java #TreeSet #JavaCollections #CoreJava #JavaDeveloper #Programming #Coding #SoftwareDevelopment #TechLearning #DataStructures #LearningJava #DeveloperCommunity
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