👇 🚀 Java Logic Series – 1: Find the Missing Number in an Array Today’s quick coding exercise — finding a missing number from a sequence using a simple mathematical approach. int[] array = {1, 2, 3, 4, 6, 7, 8, 9}; int n = array.length + 1; // total elements including missing one int expectedSum = n * (n + 1) / 2; int actualSum = 0; for (int num : array) { actualSum += num; } int missingNumber = expectedSum - actualSum; System.out.println("Missing number is: " + missingNumber); 🧠 Logic Behind It: ✅ Formula for sum of first n natural numbers → n*(n+1)/2 ✅ Subtract the actual sum of the array → get the missing number ✅ Time Complexity → O(n) 💡 Output: 👉 Missing number is: 5 Sometimes, the simplest math-based logic solves the problem elegantly. #Java #Coding #Programming #JavaDeveloper #LogicBuilding #ProblemSolving #InterviewPreparation #CleanCode
Gajanan Gaikwad’s Post
More Relevant Posts
-
Today, I practiced an interesting concept in Java — "Rotating an array from left to right and right to left using the reversal algorithm." *CONCEPT OVERVIEW Array rotation means shifting array elements by a certain number of positions. For example: Right to left Rotation: [1, 2, 3, 4, 5] → [5, 1, 2, 3, 4] Left to right Rotation: [1, 2, 3, 4, 5] → [2, 3, 4, 5, 1] To achieve this efficiently, instead of using extra arrays or nested loops, I implemented a reversal-based approach, which works in-place (O(n) time and O(1) space). *Logic Used: Right Rotation Steps: --> Reverse the entire array --> Reverse the first r elements --> Reverse the remaining elements Left Rotation Steps: --> Reverse the entire array --> Reverse the first (n – r) elements --> Reverse the last r elements *CODE STRUCTURE : rotationalArray() -> handles the main rotation logic. reverseArray() -> reverses elements between two given indices. Used Arrays.toString() for easy printing of array content. *Edge Case: If the number of rotations exceeds the array length, an error message is displayed. #Java #Coding #Programming #LearningJourney#Arrays #ReversalAlgorithm #CodePractice
To view or add a comment, sign in
-
🌳 Day 68 of Posting on LinkedIn LeetCode 112. Path Sum — Java Solution Today’s problem checks whether a root-to-leaf path exists in a binary tree such that the sum of the node values equals a target sum. This is a classic DFS (Depth-First Search) problem. We recursively explore left and right subtrees, subtracting the node’s value from the target at each step. When we reach a leaf node, we simply verify if the remaining sum matches the leaf’s value. ✅ Approach Use DFS recursion. At each node, subtract its value from the target sum. When a leaf node is reached, check if the remaining sum is zero. Return true if any path satisfies the condition. 🧠 Key Takeaways Classic DFS problem on binary trees Base case: checking leaf nodes Use subtraction to track required remaining sum #leetcode #leetcode112 #dsa #coding #java #binarytrees #programming #tech #interviewprep #softwareengineering #100daysofcode
To view or add a comment, sign in
-
-
🚀 Java Coding Practice: Finding Maximum Continuous Sequence of Numbers Today I explored a simple yet powerful Java program that calculates the maximum continuous accuracy (or sequence) of 0s and 1s in an array. 💡 🔍 Concept Used: Looping through arrays Conditional logic Use of Math.max() to track longest continuous segments 📊 Example Output: Maximum continuous accuracy of 0 is: 3 Maximum continuous accuracy of 1 is: 4 🧠 This logic is useful in problems like binary array analysis, signal processing, or data streak detection. #Java #Programming #Coding #Learning #Developer #ProblemSolving #DataStructures #LogicBuilding
To view or add a comment, sign in
-
-
🚀 Day 53 | DSA with Java Today, I solved the Aggressive Cows Problem — another classic example of Binary Search on Answers. 🐄🏠 --- 🔹 Problem Statement: Given n stalls at different positions and c cows: Place the cows in stalls so that the minimum distance between any two cows is maximized. Find the largest minimum distance possible. Example: Input: stalls = [1,2,4,8,9], c = 3 Output: 3 ✅ (Place cows at positions 1, 4, 8) --- ⚙️ Approach – Binary Search on Answers 1. Sort the stalls array. 2. Search in the distance range [1, max(stalls) - min(stalls)]. 3. For each mid distance, check if it’s possible to place all cows maintaining at least mid distance. 4. Adjust the search space based on feasibility: If possible → try larger distance Else → try smaller distance Time Complexity: O(n × log(maxDistance)) Space Complexity: O(1) --- 🧠 Learning Outcomes: ✅ Practiced Binary Search on Answers in a spatial context ✅ Strengthened logical thinking with feasibility functions ✅ Similar patterns as Book Allocation and Painters Partition --- #DSA #Java #BinarySearch #AggressiveCows #ProblemSolving #Coding #Programming #100DaysOfCode #GitHub #LogicBuilding
To view or add a comment, sign in
-
-
💻 Exploring Patterns in Java! Today, I implemented a simple yet classic program — a Hollow Square Pattern using nested loops in Java. This program helps in understanding: ✅ The logic behind nested for-loops ✅ The use of conditional statements for pattern control ✅ How small programs improve logical thinking & coding structure Here’s the output for input 3: *** * * *** Every line of code brings a new learning opportunity. 🔥 #Java #Programming #PatternPrinting #DeveloperJourney #CodingPractice #LogicBuilding #LearnWithCode
To view or add a comment, sign in
-
-
🚀 DSA Progress Update: Solved “House Robber” Problem in Java! 🏠💰 Today, I tackled another classic Dynamic Programming challenge — the House Robber problem — a beautiful blend of logic, recursion, and optimization. 🔹 Problem Statement: You are a professional robber planning to rob houses along a street. Each house has a certain amount of money, but adjacent houses are connected with security systems — robbing two neighboring houses triggers the alarm! 👉 The goal: Find the maximum money you can rob without alerting the police. 🔹 Approach Used: Used Top-Down Dynamic Programming (Memoization) to optimize recursion. At each step, you face two choices — 1️⃣ Rob the current house and skip the next one. 2️⃣ Skip the current house and consider the next. By caching results for each index, redundant recalculations are avoided, achieving O(n) time complexity. 🔹 Connection to 0/1 Knapsack: This problem is conceptually a special case of the 0/1 Knapsack problem 🎒 Both involve binary choices (take or skip) to maximize a total value under specific constraints. In Knapsack, the constraint is total weight capacity. In House Robber, the constraint is adjacency — you can’t rob two neighboring houses. That’s why the House Robber problem is often called the “linear version” of Knapsack, showcasing the same decision-making pattern in a simplified setup. 🔹 Key Learnings: Recognized the “include vs. exclude” pattern — the foundation of many DP problems. Learned how memoization can turn exponential recursion into linear-time efficiency. Strengthened my understanding of optimal substructure and state transitions in DP. ✨ This problem was a great reminder that Dynamic Programming is not about memorizing formulas — it’s about recognizing patterns of choice and optimization. 💡 #DSA #DynamicProgramming #Java #ProblemSolving #Knapsack #HouseRobber #LeetCode #CodingJourney #SpringBoot #TechJourney #DailyLearning #CrackTheCode #GrowthMindset
To view or add a comment, sign in
-
-
Finally implemented the 0/1 Knapsack problem using Dynamic Programming in Java 🧠💻 While revisiting classic algorithms, I decided to go old school with Java — and this time, I went deep into the Knapsack problem. It’s fascinating how such a seemingly simple problem teaches you so much about: Optimal substructure Overlapping subproblems And most importantly, how dynamic programming can turn exponential recursion into an elegant bottom-up solution. Watching those arrays fill up and tracing back the solution always gives that satisfying “it finally clicked” moment. 😅 Sometimes, revisiting the basics is the best way to sharpen your fundamentals. Have you ever gone back to re-implement classic DSA problems after years of working in real-world projects? #Java #DynamicProgramming #Algorithms #DSA #ProblemSolving #Knapsack
To view or add a comment, sign in
-
-
Today I learned about Strings in Java! A String in Java is an object that represents a sequence of characters enclosed in double quotes — and it plays a vital role in text processing. During my practice today, I explored and implemented various string operations such as: 🔹 Reflecting a single word input 🔹 Reflecting a single line of text 🔹 Determining the length of a string 🔹 Converting strings to Uppercase and Lowercase 🔹 Comparing two strings for equality (case-sensitive & case-insensitive) 🔹 Concatenating two strings 🔹 Lexicographical comparisons 🔹 Retrieving a specific character 🔹 Checking if a string starts with, ends with, or contains a substring 🔹 Finding the index and last index of characters 🔹 Trimming whitespace 🔹 Extracting substrings 🔹 Checking if a string is empty 🔹 Splitting a string into words 🔹 Replacing characters and converting to lowercase 💡 This hands-on learning helped me understand how Strings are not just about text — they are essential for handling input, formatting data, and building interactive applications. 🚀 Excited to keep improving my Java skills and dive deeper into more advanced concepts soon! #Java #Programming #LearningJourney #CodingInPublic #JavaDeveloper #StringInJava #CodeNewbie #SoftwareDevelopment #100DaysOfCode #TechLearning #EngineeringStudent #JavaProgramming #CodingJourney #DeveloperCommunity
To view or add a comment, sign in
-
-
💻 Exploring Java Programming: Strong Number Check 💡 Today, I practiced writing a Java program to check whether a number is a Strong Number — a number whose sum of the factorials of digits equals the number itself. For example: 👉 145 = 1! + 4! + 5! = 145 ✅ 👉 565 ≠ 5! + 6! + 5! ❌ Here’s a quick snippet from my code (shown below 👇): - Used a "while" loop for digit extraction - Calculated factorial using a nested "for" loop - Compared the final sum to the original number 🧠 Output: Enter a number to check: 145 145 is a strong number Always exciting to see how logic and math combine beautifully in programming! #Java #Coding #Programming #Learning #Engineering #StrongNumber #DeveloperJourney #CodeLogic
To view or add a comment, sign in
-
-
🚀 Exploring Jagged Arrays in Java! In Java, arrays don’t always have to be perfectly rectangular — they can have different lengths for each row. That’s what we call a Jagged Array! 🧩 Here’s a simple example where each row of the array has a different size. Using nested loops and user input, we can dynamically store and display values in this structure. This concept is super useful when working with data that’s irregular in shape — like seating charts, triangle matrices, or multi-level data sets. 💡 Key Takeaway: Jagged arrays give flexibility to your program by saving memory and adapting to real-world uneven data. #Java #Programming #Learning #Coding #Developers #OOP #JavaBasics #ProblemSolving
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