🔎 Binary Search in Java – Efficient Searching Made Simple.. Searching is one of the most common operations in programming. Today, I implemented Binary Search in Java to efficiently find a target element in a sorted array. 📌 What This Program Does ✔️ Takes array input from the user ✔️ Sorts the array using Arrays.sort() ✔️ Searches for a target element ✔️ Returns the index of the element if found ✔️ Returns -1 if the element is not present ⚙️ How the Logic Works 🔹 Initialize two pointers: left = 0 right = n - 1 🔹 While left <= right: Check if nums[left] == target Check if nums[right] == target Move left++ and right-- accordingly 🔹 If the element is not found, return -1 🚀 Key Concepts Used 🔸 Arrays 🔸 Sorting (Arrays.sort()) 🔸 Looping with conditions 🔸 Object-Oriented Programming (Separate Search Class) 🔸 User Input using Scanner 💡 Why Binary Search? Binary Search is efficient for sorted arrays and reduces time complexity compared to linear search. ⏱️ Time Complexity: O(log n) (for standard binary search) 📦 Space Complexity: O(1) Practicing these core concepts strengthens problem-solving skills and builds a strong foundation in Data Structures and Algorithms. 📚 Consistent practice leads to confident coding! A special thanks to my mentor Anand Kumar Buddarapu sir for guiding me and helping me build strong problem-solving skills in Java. Thanks also to: Saketh Kallepu Uppugundla Sairam #Java #BinarySearch #DataStructures #Programming #CodingJourney #BTech #Learning #JavaDeveloper
Java Binary Search Implementation
More Relevant Posts
-
🚀 Day 15/30 – Java DSA Challenge 🔎 Problem 66: 20. Valid Parentheses (LeetCode – Easy) Continuing Day 15 with one of the most fundamental and frequently asked interview problems — Valid Parentheses. This problem strengthens understanding of: ✅ Stack Data Structure ✅ Balanced Bracket Validation ✅ Order-Based Matching Logic 🧠 Problem Summary You are given a string containing only: '(', ')', '{', '}', '[' , ']' A string is valid if: ✔ Open brackets are closed by the same type ✔ Brackets are closed in correct order ✔ Every closing bracket has a corresponding opening bracket 🎯 Goal: Return true if the string is valid, otherwise false. 💡 Key Insight This is a classic LIFO (Last-In-First-Out) problem. Opening brackets → Push into stack Closing brackets → Check top of stack If mismatch → Invalid At the end: ✔ Stack must be empty for the string to be valid. 🔄 Approach Used 1️⃣ Traverse the string 2️⃣ Push opening brackets into stack 3️⃣ For closing bracket: If stack empty → invalid Pop and check if matching type 4️⃣ After traversal → check if stack is empty ⏱ Complexity Analysis Time Complexity: 👉 O(N) Space Complexity: 👉 O(N) 📌 Concepts Strengthened ✔ Stack Fundamentals ✔ Parentheses Matching ✔ LIFO Principle ✔ Conditional Validation Logic ✔ Edge Case Handling 📈 Learning Reflection This problem may be Easy level, but it builds the foundation for: Expression evaluation Syntax validation Compiler parsing logic Advanced stack problems Strong fundamentals → Strong problem-solving ability. ✅ Day 15 Progress Update 🔥 66 Problems Solved in 30 Days DSA Challenge Consistency + Strong Basics = Long-Term Growth 🚀 #Day15 #30DaysOfDSA #Java #LeetCode #Stack #ProblemSolving #CodingJourney #InterviewPreparation #Consistency #DSALearning
To view or add a comment, sign in
-
-
🔄 Bubble Sort Implementation in Java... Today, I implemented the Bubble Sort algorithm in Java to understand sorting logic at a deeper level. Sorting is one of the fundamental concepts in Data Structures, and implementing it manually helps strengthen problem-solving skills. 📌 What This Program Does: ✔️ Takes array input from the user ✔️ Uses nested loops to compare adjacent elements ✔️ Swaps elements if they are in the wrong order ✔️ Sorts the array in ascending order ✔️ Prints the final sorted array 🧠 Logic Behind Bubble Sort: 🔹 Compare arr[j] and arr[j+1] 🔹 If arr[j] > arr[j+1] → Swap 🔹 Repeat the process for n-1 passes 🔹 After each pass, the largest element "bubbles up" to its correct position That’s why it is called Bubble Sort. ⚙️ Concepts Used: 🔸 Arrays 🔸 Nested Loops 🔸 Swapping Technique 🔸 Object-Oriented Programming (Separate Sort Class) 🔸 User Input using Scanner. ⏱️ Complexity Analysis: Time Complexity: 🔹 Worst Case: O(n²) 🔹 Best Case: O(n²) Space Complexity: O(1) (In-place sorting) Implementing basic algorithms manually builds a strong foundation in Data Structures and improves logical thinking step by step. Every small concept learned today becomes confidence tomorrow. 💻✨. 🙏 Grateful to my mentor Anand Kumar Buddarapu sir for continuous guidance and support in strengthening my programming fundamentals. Thanks also to: Saketh Kallepu Uppugundla Sairam #Java #DataStructures #SortingAlgorithms #BubbleSort #Programming #CodingJourney #Learning #JavaDeveloper #BTech
To view or add a comment, sign in
-
-
Most of us, when we started Competitive Programming in Java, understood that using the Scanner class for taking inputs and System.out.print() for outputs can make our programs slower, so we quickly switched to BufferedReader and BufferedWriter by following a standard template, which improved the execution time. I decided to understand both to see how they differ and what makes the latter one faster. Honestly, the logic was simple. BufferedReader and BufferedWriter use a buffer to store a large chunk of an input stream in a single I/O operation, then break it up internally according to the needs, using a StringTokenizer or any other means. Scanner does internal parsing and reads input token by token. It performs extra processing like regex matching, which makes it convenient but slower. It also takes care of token validation internally. BufferedReader works differently. It reads a large chunk of data into memory at once (a buffer) and then processes it. Instead of interacting with the input stream repeatedly, it reduces the system calls made. It just reads the stream and does not do any special parsing. Moreover, Scanner is also not thread safe. This doesn’t mean Buffered Reader is better than Scanner in any way, though; it depends on specific use cases and what we want. I decided to learn Java I/O properly and tried to understand how input/output streams and reader/writer classes work. It was fun. 😊 It fascinates me how engineers have tailored systems with clever techniques for several use cases. Happy Coding :) #Java #Coding #CompetitiveProgramming #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 Day 14/30 – Java DSA Challenge 🔎 Problem 64: 1614. Maximum Nesting Depth of the Parentheses (LeetCode – Easy) Continuing Day 14 with another fundamental problem focused on Stack usage and Parentheses Processing, which is a very common interview pattern. 🧠 Problem Summary Given a valid parentheses string, the task is to determine the maximum nesting depth. 👉 Nesting depth represents how many parentheses are open simultaneously at any point. Example: (1+(2*3)+((8)/4))+1 Here, digit 8 lies inside 3 nested parentheses, so the answer is 3. 💡 Key Insight Every time we encounter: "(" → Depth increases ")" → Depth decreases So, tracking currently open parentheses helps us determine the maximum depth reached during traversal. A Stack naturally models this behavior. 🔄 Approach Used 1️⃣ Traverse the string character by character 2️⃣ Push '(' into stack when opening bracket appears 3️⃣ Pop when closing bracket appears 4️⃣ Track maximum stack size during traversal 5️⃣ Maximum stack size = Maximum nesting depth ⏱ Complexity Analysis Time Complexity: 👉 O(N) — Single traversal of string Space Complexity: 👉 O(N) — Stack storage in worst case 📌 Concepts Strengthened ✔ Stack Data Structure ✔ Parentheses Validation Logic ✔ Depth Tracking ✔ String Traversal ✔ Simulation Technique 📈 Learning Reflection Problems like this highlight how simple data structures elegantly solve structural problems. Understanding stack behavior builds strong foundations for: Expression evaluation Compiler parsing Balanced parentheses problems ✅ Day 14 Progress Update 🔥 64 Problems Solved — Still Consistent Small daily improvements → Long-term mastery 🚀 #Day14 #30DaysOfDSA #Java #LeetCode #Stack #DSAJourney #ProblemSolving #CodingConsistency #InterviewPreparation #LearningEveryday
To view or add a comment, sign in
-
-
🚀 Turning Numbers into Words using Java | A Logic-Building Exercise Ever wondered how numbers like 9999 can be converted into 👉 “nine thousand nine hundred ninety nine” — purely using logic? I recently built a Number to Words program in Java, and it turned out to be a surprisingly powerful learning experience 💡 🔍 What makes this interesting? No built-in libraries for conversion Handled numbers digit by digit Used place values (ones, tens, hundreds, thousands) Reconstructed the final output using StringBuilder and logic reversal 🧠 What this improved for me: Stronger understanding of number decomposition Better grip on arrays & indexing Practical use of loops, conditionals, and StringBuilder Thinking in terms of base values (units, tens, hundreds…) Writing cleaner, more readable logic instead of hardcoding ⚙️ How I approached it: Broke the number into digits using modulo and division Mapped digits to words using arrays Appended words based on their position (ones, tens, hundreds, thousands) Reversed the result to get the correct order ✨ This kind of problem may look simple, but it sharpens problem-solving skills and prepares you for real interview logic questions. 📢 Suggestion to fellow learners: If you’re learning Java (or any language), try building this without searching for ready-made solutions. You’ll learn more from the struggle than the result 😉 💬 If you’ve tried similar logic-based problems or want help improving this further, let’s discuss! Source Code: https://lnkd.in/g9ZnMFKF #Java #ProblemSolving #LogicBuilding #DSA #LearningByDoing #Programming #Students #CodingJourney Sharath R MD SADIQUE Harshit T
To view or add a comment, sign in
-
-
🚀 Day 16/30 – Java DSA Challenge 🔎 Problem 69: 150. Evaluate Reverse Polish Notation (LeetCode – Medium) Today’s problem focused on evaluating expressions written in Reverse Polish Notation (RPN) — also known as Postfix Expression. This problem strengthens: ✅ Stack fundamentals ✅ Expression evaluation ✅ Operator handling ✅ Order of operations without parentheses 🧠 Problem Summary We are given an array of strings representing a mathematical expression in Reverse Polish Notation. We must evaluate the expression and return the result. Key Points: Valid operators: +, -, *, / Division truncates toward zero No division by zero Expression is always valid 💡 Why Stack is Perfect Here? In RPN: Operands come first Operator comes after its operands Example: ["2","1","+","3","*"] Which translates to: ((2 + 1) * 3) = 9 Core Logic: 1️⃣ If token is a number → Push to stack 2️⃣ If token is an operator → Pop top two numbers Apply operation Push result back to stack At the end, the stack contains the final result. ⏱ Complexity Analysis Time Complexity: O(N) Space Complexity: O(N) Each token is processed exactly once. 📌 Concepts Reinforced ✔ Stack-based expression evaluation ✔ Understanding postfix notation ✔ Order of operand handling (important for subtraction & division) ✔ Clean and structured operator handling 📈 Learning Reflection This problem shows how powerful stacks are when dealing with expressions. Unlike infix expressions (which require precedence rules and parentheses), postfix expressions simplify evaluation — making stack the ideal data structure. Mastering these fundamentals builds strong foundations for: Expression parsing Compiler design basics Advanced algorithm problems ✅ Day 16 Progress Update 🔥 69 Problems Solved in 30 Days DSA Challenge Consistency. Logic. Growth. 🚀 #Day16 #30DaysOfDSA #Java #LeetCode #Stack #Algorithms #ProblemSolving #CodingJourney #InterviewPreparation
To view or add a comment, sign in
-
-
Day 40 - 🚀 Polymorphism in Java – One Interface, Many Forms Polymorphism is one of the core concepts of Object-Oriented Programming (OOP) in Java. It allows an object to take many forms, meaning the same method name can perform different tasks depending on the object. 📌 Definition Polymorphism is the ability of a method or object to behave differently based on the context, even though it has the same name. Types of Polymorphism in Java 🔹 Compile-Time Polymorphism (Method Overloading) Multiple methods with the same name but different parameters. class Calculator { int add(int a, int b){ return a + b; } int add(int a, int b, int c){ return a + b + c; } } 🔹 Runtime Polymorphism (Method Overriding) A child class provides a specific implementation of a method defined in the parent class. class Animal { void sound(){ System.out.println("Animal makes sound"); } } class Dog extends Animal { void sound(){ System.out.println("Dog barks"); } } Animal a = new Dog(); a.sound(); // Output: Dog barks Key Points ✔ Achieved through method overloading and method overriding ✔ Helps in code reusability and flexibility ✔ Uses inheritance and dynamic method dispatch 💡 Polymorphism makes Java programs more flexible, scalable, and maintainable. #Java #OOP #Programming #Polymorphism #JavaDeveloper #Coding #SoftwareDevelopment
To view or add a comment, sign in
-
-
🚀 Learning Core Java – The Four Pillars of Object-Oriented Programming Object-Oriented Programming (OOP) is the foundation of Java. It helps developers design clean, modular, and scalable applications. Java is built on four major pillars: ⸻ 🔹 1️⃣ Encapsulation Encapsulation means binding data (variables) and behavior (methods) together into a single unit, typically a class. It also involves data hiding, where class variables are kept private and accessed through public getter and setter methods. 👉 Purpose: Protect data and control access. ⸻ 🔹 2️⃣ Inheritance Inheritance allows one class to acquire properties and behaviors of another class using the extends keyword. It promotes code reusability and establishes a parent-child relationship between classes. 👉 Purpose: Reuse and extend existing code. ⸻ 🔹 3️⃣ Polymorphism Polymorphism means “many forms.” It allows methods to behave differently based on the object calling them. It can be achieved through: • Method Overloading (Compile-time polymorphism) • Method Overriding (Runtime polymorphism) 👉 Purpose: Improve flexibility and dynamic behavior. ⸻ 🔹 4️⃣ Abstraction Abstraction means hiding implementation details and showing only essential features. It can be achieved using: • Abstract classes • Interfaces 👉 Purpose: Reduce complexity and focus on what an object does rather than how it does it. ⸻ 🔎 Key Insight: Encapsulation protects data. Inheritance promotes reuse. Polymorphism adds flexibility. Abstraction simplifies complexity. Together, these four pillars make Java powerful and scalable for real-world applications. Excited to keep strengthening my OOP fundamentals! 🚀 #CoreJava #ObjectOrientedProgramming #OOP #JavaDeveloper #ProgrammingFundamentals #LearningJourney #SoftwareEngineering #TechLearning
To view or add a comment, sign in
-
-
🚀 Learning Update: Core Java — Method Overloading & Compile Time Polymorphism Today’s session helped me understand one of the most important OOP concepts in Java — Method Overloading, along with related concepts like compile-time polymorphism, type promotion, and ambiguity. 📌 Key Learnings: ✅ Method Overloading Learned that method overloading is the process of creating multiple methods with the same name within the same class, but with different parameters (number or type). ✅ Compile-Time Polymorphism (Static Binding / Early Binding) Understood that method overloading happens during the compilation phase and is handled by the Java compiler, not the JVM. ✅ Three Rules of Method Overloading Resolution: 1️⃣ Method Name 2️⃣ Number of Parameters 3️⃣ Type of Parameters These rules help the compiler decide which method should be executed. ✅ Type Promotion Learned how Java automatically converts data types to the closest compatible type when an exact method match is not available. ✅ Ambiguity in Method Overloading Explored scenarios where the compiler gets confused when multiple methods match equally, leading to ambiguity errors. ✅ Real-World Understanding A very interesting realization was that we already use method overloading in Java daily — for example, System.out.println() has multiple overloaded versions internally. 💡 Important Insight: Understanding concepts deeply with logic and real examples is much more powerful than just memorizing definitions — especially for technical interviews. Consistent practice and conceptual clarity are key to becoming a confident developer. #Java #CoreJava #Programming #MethodOverloading #OOP #LearningUpdate #CodingJourney #StudentDeveloper TAP Academy
To view or add a comment, sign in
-
-
DAY 19: CORE JAVA 🔐 Encapsulation in Object-Oriented Programming (OOP) Encapsulation is one of the four pillars of Object-Oriented Programming — along with Inheritance, Polymorphism, and Abstraction. At its core, Encapsulation is about: ✔ Protecting the most important components of an object ✔ Providing controlled access to data ✔ Enhancing security and maintainability 💡 What is Encapsulation? Encapsulation is the process of binding data (variables) and methods (functions) together inside a class and restricting direct access to some of the object's components. Instead of allowing direct access to variables, we use: private access modifiers public getter and setter methods This ensures that: 👉 No unauthorized access 👉 No uncontrolled modifications 👉 Data integrity is maintained 🔒 Example: Bank Account (Safe Approach) class BankAccount { private int balance; public void setBalance(int data) { if (data >= 0) { balance = data; } else { System.out.println("Invalid input"); } } public int getBalance() { return balance; } } ✔ balance is private ✔ Access is controlled via methods ✔ Validation ensures security Without encapsulation, anyone could directly modify: ba.balance = -100000; // Unsafe! Encapsulation prevents this risk. 🧠 Shadowing Problem & the this Keyword When local variables have the same name as instance variables, we face a shadowing problem. Example: class Customer { private int cId; private String cName; private long cNum; public void setData(int cId, String cName, long cNum) { this.cId = cId; this.cName = cName; this.cNum = cNum; } } 👉 this refers to the current object 👉 It resolves naming conflicts 👉 Ensures instance variables are correctly updated 🎯 Why Encapsulation Matters ✅ Improves security ✅ Promotes data hiding ✅ Provides controlled access ✅ Makes code maintainable ✅ Prevents accidental misuse ✅ Encourages clean design Encapsulation isn’t just a concept — it’s a design discipline that makes your applications robust and secure. As developers, protecting data is not optional — it’s a responsibility. TAP Academy Sharath R #Java #OOP #Encapsulation #Programming #SoftwareDevelopment #CodingPrinciples #Developers
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