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
Consecutive Subarrays in Java | TAP Academy
More Relevant Posts
-
Day 22 | Programming Classes at TAP Academy 🧾 Count Variations in Strings ✨ 💥 Problem 1: Count Words in a String General Approach: words = spaces + 1; Looks correct but… 👉 What if multiple spaces exist? 👉 What if spaces appear at the start/end? logic breaks. ✅ Correct Insight A word starts when: current character = space next character ≠ space 💡 Final Code public static int countWords(String s) { int count = 0; for (int i = 0; i < s.length() - 1; i++) { if (s.charAt(i) == ' ' && s.charAt(i + 1) != ' ') { count++; } } // Handle starting space edge case if (s.charAt(0) == ' ') { return count; } else { return count + 1; } } 💥 Problem 2: Count Vowels in a String 💡 Logic A character is a vowel if: 👉 It matches a, e, i, o, u (both cases) ✅ Code int count = 0; for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') { count++; } } 💥 Problem 3: Count Consonants Mostly say: 👉 “Not vowel = consonant” ❌ Wrong. Because: digits -> not vowels special characters -> not vowels But they are NOT consonants. ✅ Proper Approach Check if character is alphabet Then check: vowel -> vowel count else -> consonant 💡 Code public static int countConsonants(String s) { int cc = 0; for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); // Check if alphabet if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) { // Check if NOT vowel → consonant if (!(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U')) { cc++; } } } return cc; } 💥 Final Boss Problem 👉 Count: Vowels Consonants Numbers Special characters 💡 Code public static void countCharacters(String s) { int vc = 0, cc = 0, nc = 0, sc = 0; for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) { if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') { vc++; } else { cc++; } } else if (ch >= '0' && ch <= '9') { nc++; } else { sc++; } } } #Java #Programming #CodingInterview #DataStructures #ProblemSolving #LearnToCode #Developers #CodingJourney #TechSkills #Code #InterviewPreparation #CoreJava #Upskilling #Learning #DSA #Strings #Logics #Thinking #TAPAcademy
To view or add a comment, sign in
-
-
Day 23 | Programming Classes at TAP Academy 🚨 Mastering String Problems: Logic Over Syntax You’re given a string: 👉 "he#l@lo123" Task? Remove only special characters. Sounds basic But this is where logic—not syntax—gets tested. 💥 The Real Trap Most of us write: if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z') { result += ch; } Looks correct. But this removes numbers too ❌ 👉 Problem: remove only special characters 👉 Your code: removes everything except alphabets That’s not solving. That’s assuming. 🧠 Core Concept Every character falls into 3 buckets: Alphabet Numeric Special character So don’t try to detect special characters (it’s messy across Unicode ❌) 👉 Instead, keep what you know is valid if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9')) { result += ch; } 🔍 Underlying Logic Pattern Strings are immutable. So the real workflow is: ➡️ Traverse (for loop) ➡️ Extract (charAt(i)) ➡️ Validate (conditions) ➡️ Build new string String result = ""; for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if (Character.isLetterOrDigit(ch)) { result += ch; } } ⚡ Level Up: Rearranging the String New problem: 👉 Uppercase -> Lowercase -> Numbers (remove specials) Two approaches: Approach 1 (naive): 3 loops -> O(3n) Approach 2 (optimized): 1 loop + 3 strings -> O(n) String uc="", lc="", nc=""; for(char ch : s.toCharArray()){ if(ch >= 'A' && ch <= 'Z') uc += ch; else if(ch >= 'a' && ch <= 'z') lc += ch; else if(ch >= '0' && ch <= '9') nc += ch; } return uc + lc + nc; 👉 Same result. Better thinking. 💣 The Dangerous Bug (ASCII Trap) You try to sum numbers: sum += ch; Output? ❌ 155 instead of 11 Why? 👉 '2' = 50, '4' = 52, '5' = 53 👉 You added ASCII, not actual numbers 🔥 Fix: sum += (ch - '0'); 👉 Converts char -> actual digit ⚠️ Operator Precedence Trap This looks harmless: result += ch + 32; But gives ❌ "H32E32..." Why? 👉 String + char + int -> left to right evaluation 🔥 Fix: result += (char)(ch + 32); 🔄 Case Conversion Logic (No Inbuilt Methods) Key insight: 👉 'A' → 'a' difference = 32 So: Upper → Lower → +32 Lower → Upper → -32 if(ch >= 'A' && ch <= 'Z'){ result += (char)(ch + 32); }else{ result += ch; } 🔁 Swap Case Logic if(ch >= 'A' && ch <= 'Z'){ result += (char)(ch + 32); } else if(ch >= 'a' && ch <= 'z'){ result += (char)(ch - 32); } else{ result += ch; } 👉 Clean. No shortcuts. Pure logic. #Java #CodingInterview #ProblemSolving #Developers #LearnToCode #Programming #TechCareers #CodeSmart #CoreJava #Strings #Logics #Thinking #Coding #Upskilling #Problems #Syntax #DSA #TAPAcademy #Software #Development #Learning
To view or add a comment, sign in
-
-
🚀 Learning OOP: Inheritance & Its Types Today, I explored one of the most powerful concepts in Object-Oriented Programming — Inheritance. 👉 What is Inheritance? Inheritance allows a class (child class) to acquire properties and methods from another class (parent class). It helps in code reusability, scalability, and cleaner structure. 🔹 Types of Inheritance I learned: 1. Single Inheritance One child class inherits from one parent class. 2. Multiple Inheritance One child class inherits from multiple parent classes. 3. Multilevel Inheritance A chain of inheritance (grandparent → parent → child). 4. Hierarchical Inheritance Multiple child classes inherit from a single parent class. 💡 Key Takeaways: - Reduces code duplication - Makes programs more modular - Improves maintainability 📌 Understanding inheritance is a big step toward mastering OOP and writing efficient code. #Python #OOP #Inheritance #CodingJourney #Programming #Learning
To view or add a comment, sign in
-
-
I’ve started writing to improve how I understand and explain concepts. My first blog focuses on a fundamental topic in programming—recursion vs iteration—and how they represent two different ways of thinking while solving problems. This is just the beginning. I’ll be writing on a mix of technical topics and general ideas going forward. Read here: https://lnkd.in/gw98ph77 #Programming #Learning #Algorithms #StudentJourney
To view or add a comment, sign in
-
Understanding Variables in Programming: The Mental Model Beginners Miss Why beginners struggle with variables isn’t syntax — it’s misunderstanding what variables actually represent inside a running program....
Understanding Variables in Programming: The Mental Model Beginners Miss https://thetechthriller.buzz To view or add a comment, sign in
-
Finished Reading: Beginning C++23: From Beginner to Pro (7th Ed.) — Horton & Van Weert If you've ever had aspirations of mastering the art of C++ programming, you need to know that while many books exist, very few can give you an authentic experience of the language. C++ is infamous for being difficult and overwhelming. However, the authors of this book take their readers through a detailed journey towards mastering the language without overwhelming them. The topics covered throughout the 20+ chapters include: -> Fundamentals — data types, variables, operations, and memory management in C++ -> Logic and control flow — decision structures, loops, spaceship operator, etc. -> Advanced concepts — pointees and references, smart pointers to prevent memory leaks -> Modular programming — functions, function overloading, recursion, etc. -> Object-oriented programming — classes, encapsulation, polymorphism, operator overloading -> Modern C++ — templates, lambdas, move semantics, ranges, and new C++23 features -> Standard library — covers more than 35 different modules, ranging from strings and vectors to algorithms, file I/O, etc. The distinguishing factor of this edition is its focus on teaching modern idioms of C++23 — import std;, std::println(), std::optional, and other similar features. You'll not be learning an old version of the language that was written in the '90s. This book is highly recommendable to anyone looking to switch career paths towards systems programming, game development, or embedded systems. Also suitable for those interested in understanding the inner workings of softwaare products. I would personally recommend this book for absolute beginners with some programming background, transitioning developers, and former C++ users. What do you think of the book? Do you have another C++ resource to recommend? PS: Here is a sneak peak into my study table 😆 , I like to study in a private library to keep proximity to other motivated learners.
To view or add a comment, sign in
-
-
Announcing CodeVille: Making Programming More Accessible Through Storytelling Over the past few months, I’ve been working on an idea to make programming concepts more approachable especially for beginners. The question I kept coming back to was: what if complex topics could be explained through simple, visual storytelling? I’m pleased to share the launch of CodeVille, a series designed to explain programming concepts using cartoon-style narratives with the goal of reducing barriers and making learning more intuitive. The first three episodes are now live: • What Is Programming? • Class vs Object (Meet Classy & Ollie) • Properties & Methods This series may be particularly helpful for students, beginners, and anyone who has found programming concepts difficult to grasp through traditional approaches. If you have a few minutes, I would truly appreciate you taking a look. Your feedback would mean a lot, and if you feel it could benefit others, please consider sharing it within your network. Thank you for your continued support. https://lnkd.in/gMkwSuCD #Programming #STEMEducation #ComputerScience #Learning #EducationInnovation #AI #OOP #HigherEducation
To view or add a comment, sign in
-
Kathleen Booth - Inventor of Modern Programming Before computers were widespread, they were clunky and hard to use. Programming a computer involved physically flipping switches to get the computer to perform certain actions encoded in binary. However, this all changed when programming languages came along. The most basic programming language after machine code is assembly, which is a way to encode machine code instructions in such a way that it almost looks like human words. With better ways to program a computer, computers quickly began to pick up in popularity; first with hobbyists, then with families who adopted them as entertainment centers. This includes game consoles. Did you know that the first assembly programming language was invented by a woman? Her name is Kathleen Booth. She was born in 1922 in Stourbridge, England. Kathleen was a mathematician, which led her to using computers as back then, they were primarily tools meant for mathematics. This frequent use of computers led her to create a language to represent the machine code instructions that mathematicians often manually inputted for the CPU to execute. Having created a better way to program a computer, the assembly language she created for the All Purpose Electronic Computer (APEC) and Simple Electronic Computer (SEC) that she built with her husband created a chain reaction that led to more accessible and capable programming languages such as BASIC and C, which powered hobbyist and high-performance professional programs and games respectively in the 80s. Fast-forward to today, programming is more accessible than ever. With easy languages like Python, all the way to visual, block-based languages like Scratch, anyone could make their dream program even on small devices like their smartphones. So when writing a program, remember where it all started and remember the woman that pioneered modern-day programming. By : Samuel Reagan P
To view or add a comment, sign in
-
-
🚀 New Blog: How Short Videos Can Enhance Programming Skills Short-form videos like Reels and YouTube Shorts are not just for entertainment-they are becoming powerful tools for learning. 🔗 Read here: https://lnkd.in/g7Z9JtAC #Programming #Python #Learning #CodingSkills #YouTubeShorts #Reels #Microlearning #TechEducation SR University #SRUniversity #SRU
To view or add a comment, sign in
-
Programmers Don’t Need to Know Much Math The most common anxiety I hear about learning to program is the notion that it requires a lot of math. Actually, most programming doesn't require math beyond basic arithmetic. In fact, being good at programming isn't that different from being good at solving Sudoku puzzles. To solve a Sudoku puzzle, the numbers from one to nine are placed in a grid with a field for each row, so each row and each 3x3 interior square of the full 9x9 game, some numbers are provided to give you a start, and you find a solution by making deductions based on these numbers. What this really means is that programming is more about thinking than calculating. Just like Sudoku, you are not doing heavy mathematics. You are looking for patterns, understanding rules, and making logical decisions step by step. You observe what is already given, you test possibilities, and you adjust when something does not work. That is exactly how coding works, too. When you write code, you are not sitting there solving complex equations. You are breaking problems into smaller parts, following instructions, and building solutions one step at a time. It is more about logic, patience, and practice than advanced math skills. So, if you have been holding back because you think you are not “good at math,” you might be worrying about the wrong thing. If you can think through problems, stay curious, and keep trying even when something does not work at first, you already have what it takes to start programming.
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