📌 DSA Problem Series – Day 15 | Problem 2 | Array 🔹 Problem: Missing and Repeating Number 🧠 Problem Statement: You are given an array of size N containing numbers from 1 to N. One number is missing One number is repeating Your task is to find both numbers. ✅ Approach Used Use a HashMap to track frequency of elements Identify the repeating number when frequency > 1 Use mathematical sum formula to compute the missing number 💻 Java Solution class Solution { ArrayList<Integer> findTwoElement(int arr[]) { Map<Integer, Integer> map = new HashMap<>(); int n = arr.length; int expectedSum = n * (n + 1) / 2; int repeatingNumber = -1; int actualSum = 0; for (int item : arr) { if (map.containsKey(item)) { repeatingNumber = item; } map.put(item, map.getOrDefault(item, 0) + 1); actualSum += item; } int missingNumber = expectedSum - (actualSum - repeatingNumber); return new ArrayList<>(Arrays.asList(repeatingNumber, missingNumber)); } } ⏱️ Complexity Time Complexity: O(N) Space Complexity: O(N) 🎯 Key Takeaway Combining hashing with basic mathematics makes this problem simple and efficient. This pattern appears frequently in interviews and competitive programming. #DSA #Java #ProblemSolving #Arrays #CodingInterview #LeetCode #HashMap #Backend
Missing and Repeating Number in Array with Java Solution
More Relevant Posts
-
🚀 Day 56 Out of #365DaysOfCode Github Link: https://lnkd.in/gGUy_MKZ Today I solved an interesting problem sort an integer array based on the number of 1’s in its binary representation. If two numbers have the same number of set bits, sort them in ascending numerical order. 🔎 Key Concept: Use Integer.bitCount() to count the number of 1’s. Apply a custom comparator with Arrays.sort(). Handle tie-breaking by normal ascending comparison. 💡 This problem is a great reminder of how powerful Java’s built-in methods and custom comparators can be for writing clean and efficient solutions. Time Complexity: O(n log n) It’s always exciting to explore bit manipulation problems—they strengthen logical thinking and deepen understanding of how numbers work internally. #Java #Coding #DataStructures #Algorithms #BitManipulation #ProblemSolving #Learning
To view or add a comment, sign in
-
-
#Coding1 Q: Find the Largest Element in an Array (Java) Today I revised one of the most basic yet important problems in Data Structures: Problem: Find the largest element in an array Example: int[] arr = {1, 34, 56, 78, 90}; I explored 5 different approaches in Java: ✅ 1. Linear Scan (O(n) – Best for interviews) int max = arr[0]; for(int i = 1; i < arr.length; i++) { if(arr[i] > max) max = arr[i]; } ✅ 2. Using Sorting (O(n log n)) Arrays.sort(arr); int max = arr[arr.length - 1]; ✅ 3. Using Java Streams (Functional approach) int max = Arrays.stream(arr).max().getAsInt(); ✅ 4. Using Priority Queue (Max Heap) PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder()); for(int num : arr) { pq.add(num); } int max = pq.peek(); ✅ 5. Divide & Conquer (Recursive) static int findMax(int[] arr, int l, int r) { if(l == r) return arr[l]; int mid = (l + r) / 2; return Math.max(findMax(arr, l, mid), findMax(arr, mid + 1, r)); } Key Learning: Although multiple approaches exist, Linear Scan is the most efficient and interview-preferred solution with O(n) time and O(1) space. Consistent practice of fundamentals builds strong problem-solving skills More DSA posts coming soon. #DSA #Java #ProblemSolving #Coding #LinkedInLearning #SoftwareEngineering #Placements #InterviewPrep #LearningInPublic
To view or add a comment, sign in
-
🚀 Day 18 of My DSA Journey – Subarray Sum Equals K (Prefix Sum + HashMap) Today I solved the classic “Subarray Sum Equals K” problem using Prefix Sum and a HashMap in Java. 🔍 Problem Statement: Given an integer array and an integer k, return the total number of continuous subarrays whose sum equals k. 💡 Approach I Used: Instead of checking all subarrays (which would be O(n²)), I optimized it using: 1️⃣ Prefix Sum technique 2️⃣ HashMap to store frequency of prefix sums Core idea: If at any index: currentSum - k = previousPrefixSum Then there exists a subarray ending at the current index whose sum is k. So for every element: • Keep adding to running sum • Check if (sum - k) exists in the map • If yes → add its frequency to result • Update the map with current sum frequency I also initialized: map.put(0, 1) This handles cases where a subarray starting from index 0 itself equals k. --- 🎯 Key Learnings: ✅ Prefix Sum converts subarray problems from O(n²) → O(n) ✅ HashMap helps track past computations efficiently ✅ Understanding the math behind sum - k is crucial ✅ Always think: “Can I reuse previous computation?” Time Complexity: O(n) Space Complexity: O(n) Consistency + Pattern Recognition = Growth 📈 Day 18 complete ✔ On to the next challenge. #DSA #Java #PrefixSum #HashMap #ProblemSolving #CodingJourney #100DaysOfCode
To view or add a comment, sign in
-
-
Consistency is the secret sauce for placement preparation, and today focused on diving deeper into functional logic and mathematical computing in Java. Understanding these concepts goes beyond syntax; it's about optimizing our approach to solving complex problems. Here’s a breakdown of what I tackled today: 📑 Day 02/200: Deep Dive into Java Logic 1) Functions with Parameters: Mastered how to pass data into methods to enhance code modularity and reusability. 2) Factorial Logic: Implemented both iterative and recursive approaches to calculate n!. 3) Binomial Coefficient: Applied function call nesting to solve combinations using the formula. 4) Range Analysis: Explored data limits and how to manage constraints within loops. 5) Bit Conversion: Experienced the "aha!" moment of the day—converting numbers between Binary and Decimal systems. 💡 Key Takeaway The Binomial Coefficient problem reinforced the importance of using functions. Instead of writing the factorial loop multiple times, one well-defined function handled all the work, showcasing efficiency. Current Status: 02 / 200 Days Completed ✅ #PlacementPrep #JavaProgramming #CodingJourney #100DaysOfCode #EngineeringLife #ProblemSolving #SoftwareDevelopment github: https://lnkd.in/dT9Wd8Nq
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
-
-
🚀 Day 8 – LeetCode Practice Today, I solved the Search Insert Position problem on LeetCode: 🎯 Difficulty: Easy 💻 Language Used: Java 💡 Approach: • Given a sorted array and a target value, the task was to return the index where the target should be inserted if it is not found. • I used an efficient binary search approach to locate the correct position in O(log n) time. • If the target exists, return its index; otherwise, return the index where it would be inserted to maintain sorted order. ⏱ Complexity: • Time Complexity: O(log n) • Space Complexity: O(1) 📚 Key Takeaway: This problem reinforced how binary search can be slightly adapted to both find and insert positions in a sorted array without scanning the entire list — an essential optimization in sorted data structures. Consistent problem-solving practice continues to build intuition for time-efficient algorithms and clean implementations. 💪 #LeetCode #Java #DSA #BinarySearch #Algorithms #ProblemSolving #CodingPractice #100DaysOfCode #SoftwareDeveloper
To view or add a comment, sign in
-
-
Ever wondered how your computer understands the letter "A"? 🤔 It doesn't. Not directly. Your computer only speaks one language — 0s and 1s. So when we type 'A', behind the scenes it's being converted to a binary code. This is the foundation of Character Type Data in Java. Here's the logic: → 4 symbols need 2-bit codes (2² = 4) → 8 symbols need 3-bit codes (2³ = 8) → 16 symbols need 4-bit codes (2⁴ = 16) Americans standardized this into 128 symbols → ASCII (American Standard Code for Information Interchange) — a 7-bit system. But Java said: "The world speaks more than English." So Java follows UNICODE — supporting 65,536 symbols from languages across the globe. That's why a char in Java takes 2 bytes (16-bit). --- Now here's where it gets practical — Type Casting in Java. Sometimes you need to convert one data type to another. There are two ways: 🔄 Implicit Casting (automatic) — smaller → larger type. No data loss. byte → short → int → long → float → double Java handles this silently. No worries. ⚠️ Explicit Casting (manual) — larger → smaller type. You're in control, but precision is lost. Example: double a = 45.5; byte b = (byte) a; // b stores 45, 0.5 is gone forever That 0.5? Lost. That's the trade-off. --- And lastly — Boolean in Java. Just true or false. Simple. But its size? Decided by the JVM, which is platform-dependent. --- Summary: Understanding how data is stored and converted is not just theory, it directly affects how your programs behave, perform, and sometimes fail silently. #Java #Programming #LearnToCode #ComputerScience #JavaDeveloper #CodingTips #Tech #Unicode #ASCII #TypeCasting #Upskill
To view or add a comment, sign in
-
-
🚀 Day 19 of My DSA Journey – Find All Anagrams in a String (Sliding Window + Frequency Array) Today I solved the “Find All Anagrams in a String” problem using the Sliding Window technique with character frequency arrays in Java. 🔍 Problem Statement: Given two strings s and p, return all starting indices of p’s anagrams in s. 💡 Approach I Used: 1️⃣ If p.length() > s.length(), return empty list immediately. 2️⃣ Create two frequency arrays of size 26: • need[] → stores frequency of characters in p • have[] → stores frequency of current window in s 3️⃣ Build the first window of size m. 4️⃣ Compare both frequency arrays. 5️⃣ Slide the window one character at a time: • Remove left character • Add right character • Compare again 6️⃣ If both arrays match → add starting index to result list. Instead of sorting every substring (which would be expensive), I used frequency comparison to keep the solution efficient. --- 🎯 Key Learnings: ✅ Sliding Window is extremely powerful for substring problems ✅ Frequency arrays help avoid repeated sorting ✅ Comparing fixed 26 characters keeps checks constant time ✅ Pattern recognition makes similar problems easier (Permutation in String helped here!) Time Complexity: O(n) Space Complexity: O(1) (excluding result list) Day 19 complete ✔ Consistency is building confidence every single day 💯 #DSA #Java #SlidingWindow #Anagrams #ProblemSolving #CodingJourney #100DaysOfCode
To view or add a comment, sign in
-
-
☕ 𝗗𝗦𝗔 𝗨𝘀𝗶𝗻𝗴 𝗝𝗮𝘃𝗮 – 𝗖𝗼𝗺𝗽𝗹𝗲𝘁𝗲 𝗚𝘂𝗶𝗱𝗲 𝗳𝗼𝗿 𝗖𝗼𝗱𝗶𝗻𝗴 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄𝘀 Master Data Structures and Algorithms using Java with clear concepts and practical problem-solving approaches. Learn how to implement core data structures and optimize algorithms to build efficient and scalable solutions. ✅ Arrays & Strings in Java ✅ Linked List Implementation ✅ Stack & Queue Operations ✅ Recursion & Backtracking ✅ Sorting & Searching Algorithms ✅ Trees & Binary Search Trees ✅ Graph Traversal (BFS, DFS) ✅ Dynamic Programming in Java Perfect for interview preparation, competitive programming, and strengthening problem-solving skills with Java. Code smarter. Think logically. Crack interviews with confidence #DSA #Java #DataStructures #Algorithms #CodingInterview #JavaProgramming #SoftwareDeveloper #ProblemSolving #TechInterview #LearnJava #Programming
To view or add a comment, sign in
-
📌 Optimized Prime Number Check in Java (Time Complexity O(√n)) While practicing problem-solving, I implemented an optimized Prime Number check using mathematical reasoning instead of brute force. Instead of checking divisibility from 2 to n-1 (O(n)), I reduced the complexity to O(√n). 🔍 Key Optimizations Used: 1️⃣ Handle edge cases separately n == 1 → Not prime n == 2 or n == 3 → Prime 2️⃣ Eliminate obvious non-primes early If n % 2 == 0 or n % 3 == 0 → Not prime 3️⃣ Check only up to √n If a number n = a × b, then at least one of a or b must be ≤ √n. This reduces unnecessary computations significantly. ⏱ Complexity Analysis: • Time Complexity → O(√n) • Space Complexity → O(1) 💡 Why This Matters? Optimizing from O(n) to O(√n) shows: Strong mathematical thinking Better algorithm design Interview-level optimization skills Small improvements in complexity can make a huge difference for large inputs. #Java #DataStructures #Algorithms #ProblemSolving #TimeComplexity #CodingInterview #LearningJourney
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