Consecutive Subarrays in Java | TAP Academy

Day 19 | Programming Classes at TAP Academy Consecutive Sub Arrays ⚡ 🚀 From “just arrays” to real problem-solving mindset 💡 Problem 1: Find the Missing Element in an Array Given: Array starts from 1, one number is missing. 🔥 Insight: Instead of checking each number → use math. int n = arr.length + 1; int totalSum = n * (n + 1) / 2; int arraySum = 0; for(int i = 0; i < arr.length; i++) { arraySum += arr[i]; } int missing = totalSum - arraySum; System.out.println(missing); ⚡ Clean. Efficient. O(n). No sorting. No extra space. 💡 Problem 2: Print Consecutive Subarrays 👉 Key idea: Two elements are consecutive if: arr[i+1] - arr[i] == 1 for(int i = 0; i < arr.length - 1; i++) { if(arr[i+1] - arr[i] == 1) { System.out.print(arr[i] + " "); } else { System.out.println(arr[i]); } } System.out.println(arr[arr.length - 1]); 💭 Lesson: Don’t blindly use 3 loops just because it’s “subarray”. Think first. Code later. 💡 Problem 3: Length of Consecutive Subarrays int count = 1; for(int i = 0; i < arr.length - 1; i++) { if(arr[i+1] - arr[i] == 1) { count++; } else { System.out.println(count); count = 1; } } System.out.println(count); 💡 Problem 4: Longest Consecutive Subarray int count = 1, max = 0; for(int i = 0; i < arr.length - 1; i++) { if(arr[i+1] - arr[i] == 1) { count++; } else { if(count > max) { max = count; } count = 1; } } if(count > max) { max = count; } System.out.println(max); 💡 Problem 5: Print Longest Consecutive Subarray int count = 1, max = 0; int endIndex = 0; for(int i = 0; i < arr.length - 1; i++) { if(arr[i+1] - arr[i] == 1) { count++; } else { if(count > max) { max = count; endIndex = i; } count = 1; } } if(count > max) { max = count; endIndex = arr.length - 1; } int startIndex = endIndex - max + 1; for(int i = startIndex; i <= endIndex; i++) { System.out.print(arr[i] + " "); } 🧠 Big takeaway from today: Patterns > Memorization Logic > Loops Thinking > Typing 🔥 Next level thinking: What if array doesn’t start from 1? What if we need longest increasing subarray? What about prime-only subarrays? That’s where real DSA begins. #DSA #Java #CodingJourney #ProblemSolving #Placements #LearningInPublic #CodingLogic #DataStructures #ProblemSolving #InterviewPrep #TAPAcademy #Upskilling #Java #Logics #Arrays #Traversal #Learning #Upskilling #Programming

  • graphical user interface

To view or add a comment, sign in

Explore content categories