✨ Good day.... Developers! Creating and traversing arrays is important… But how do we find an element inside an array? 🤔 That’s where Searching comes in 🔍 1️⃣ Linear Search (Sequential Search) 👉 Checks each element one by one 👉 Works on both sorted & unsorted arrays int[] arr = {10, 20, 30, 40}; int key = 30; for(int i = 0; i < arr.length; i++){ if(arr[i] == key){ System.out.println("Element found at index: " + i); break; } } ==> ⏱ Time Complexity: O(n) ✔ Simple ✔ Beginner-friendly ✔ No sorting required 2️⃣ Binary Search 👉 Works only on sorted arrays 👉 Divides the array into halves import java.util.Arrays; int[] arr = {10, 20, 30, 40, 50}; int key = 30; int index = Arrays.binarySearch(arr, key); System.out.println("Element found at index: " + index); ==> ⏱ Time Complexity: O(log n) ✔ Faster than linear search ✔ Requires sorted data 🔥 Interview Insight 📌 When array is small → Linear search is fine 📌 When array is large & sorted → Binary search is better 📌 Binary search on unsorted array → ❌ Wrong logic #Java #DSA #Programming #CodingInterview #LearningJourney #SoftwareDevelopment
Searching Arrays in Java: Linear vs Binary Search
More Relevant Posts
-
✨ Hello Future Developers! We learned: ✔ What is an Array ✔ Traversing ✔ Searching Now it’s time to arrange elements in order 🔥 ==> What is Sorting? :Sorting means arranging elements in: ➡ Ascending Order (1 → 10) ➡ Descending Order (10 → 1) 1️⃣ Bubble Sort 👉 Repeatedly swaps adjacent elements 👉 Largest element “bubbles” to the end ex: int[] arr = {5, 3, 8, 1}; for(int i = 0; i < arr.length-1; i++){ for(int j = 0; j < arr.length-i-1; j++){ if(arr[j] > arr[j+1]){ int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } for(int num : arr){ System.out.print(num + " "); } ⏱ Time Complexity: O(n²) ✔ Easy to understand ❌ Not efficient for large data 2️⃣ Built-in Sorting (Recommended) Java provides a faster way 👇 ex: import java.util.Arrays; int[] arr = {5, 3, 8, 1}; Arrays.sort(arr); System.out.println(Arrays.toString(arr)); ⏱ Time Complexity: O(n log n) 🔥 Interview Insight 📌 Small array → Any method works 📌 Large data → Use efficient algorithms 📌 Always know time complexity #Java #Arrays #DSA #Coding #InterviewPreparation #LearningJourney
To view or add a comment, sign in
-
-
🚀 𝗔𝗿𝗿𝗮𝘆𝗟𝗶𝘀𝘁 𝘃𝘀 𝗟𝗶𝗻𝗸𝗲𝗱𝗟𝗶𝘀𝘁 — 𝗪𝗵𝗶𝗰𝗵 𝗢𝗻𝗲 𝗦𝗵𝗼𝘂𝗹𝗱 𝗪𝗲 𝗨𝘀𝗲? While revising the Java Collection Framework, I realized something important. We often use ArrayList by default. But do we really understand when to use LinkedList instead? Both implement the List interface, but internally they are completely different. 🔹 𝗔𝗿𝗿𝗮𝘆𝗟𝗶𝘀𝘁 ArrayList is backed by a dynamic array. That means: • Accessing elements using index is very fast • But inserting or deleting in the middle requires shifting elements So it works best when: ✔ We mostly read data ✔ Random access is frequent 🔹 𝗟𝗶𝗻𝗸𝗲𝗱𝗟𝗶𝘀𝘁 LinkedList is backed by a doubly linked list. That means: • Insertion and deletion are faster • Accessing elements by index is slower So it works best when: ✔ We frequently add/remove elements ✔ We modify data often 𝗦𝗶𝗺𝗽𝗹𝗲 𝗖𝗼𝗱𝗲 𝗘𝘅𝗮𝗺𝗽𝗹𝗲 ->List<Integer> list1 = new ArrayList<>(); ->List<Integer> list2 = new LinkedList<>(); Same interface. Different internal working. Different performance behavior. 💡 𝗪𝗵𝗮𝘁 𝗜 𝗟𝗲𝗮𝗿𝗻𝗲𝗱 Choosing the right data structure is not about syntax. It’s about understanding the use case. The more I revise Collections, the more I realize that fundamentals matter more than memorizing methods. #Java #CollectionFramework #ArrayList #LinkedList #Programming #DSA #LearningJourney
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
-
-
🚀 Day 15/30 – Java DSA Challenge 🔎 Problem 68: 232. Implement Queue using Stacks (LeetCode – Easy) Continuing Day 15 with another classic data structure transformation problem — implementing a Queue (FIFO) using only Stacks (LIFO) operations. This problem strengthens: ✅ Understanding of LIFO vs FIFO ✅ Stack manipulation ✅ Reversing order using auxiliary stack ✅ Core data structure fundamentals 🧠 Problem Summary We need to design a queue using only stack operations: push(x) pop() peek() empty() ⚠ Constraint: Only standard stack operations allowed — push, pop, peek, size, isEmpty. 💡 Key Insight Queue → First In First Out (FIFO) Stack → Last In First Out (LIFO) To simulate FIFO using LIFO: 👉 Use two stacks: input stack → for push operations output stack → for pop & peek operations When removing elements: If output stack is empty Transfer all elements from input stack to output stack This reverses order and maintains FIFO 🔄 Approach 1️⃣ Push → Always push into input stack 2️⃣ Pop/Peek → If output stack is empty, transfer elements Then pop/peek from output stack 3️⃣ Empty → Check both stacks ⏱ Complexity Analysis Push: O(1) Pop: Amortized O(1) Peek: Amortized O(1) Space Complexity: O(N) 📌 Concepts Reinforced ✔ Stack behavior ✔ Order reversal technique ✔ Amortized time complexity ✔ Clean data structure design 📈 Learning Reflection Even simple-tagged problems reveal deep structural concepts. Understanding how to simulate one data structure using another builds strong problem-solving foundations — crucial for interviews and system design thinking. ✅ Day 15 Progress Update 🔥 68 Problems Solved in 30 Days DSA Challenge Small daily improvements → Big long-term mastery 🚀 #Day15 #30DaysOfDSA #Java #LeetCode #Stack #Queue #DataStructures #CodingJourney #InterviewPreparation
To view or add a comment, sign in
-
-
📢 Shallow Copy vs Deep Copy & clone() method Internal working — Simplified! Many developers use object copying without fully understanding what happens behind the scenes… until a bug appears! Here’s what I learned: • clone() performs shallow copy by default • JVM checks Cloneable before cloning • Missing it → CloneNotSupportedException • Deep copy requires manual handling This concept is super important when working with complex objects, APIs, and real-world applications. Ever used clone() in Java and still faced unexpected data changes? That’s because clone() performs a shallow copy by default… and that’s where most developers go wrong. The real magic happens when you override clone(): • Step 1: Use super.clone() (shallow copy) • Step 2: Manually copy nested objects • Step 3: Replace shared references !---That’s how Deep Copy actually works internally---! Understanding this changed the way I handle object copying in Java applications. 📌 If you're preparing for Java interviews, don’t skip this! Swipe through the slides to master it #Java #OOP #Programming #SoftwareEngineering #JavaDeveloper #InterviewPreparation #Tech
To view or add a comment, sign in
-
🚀 Day 22 of #75DaysofLeetCode LeetCode Problem Solved: Determine if Two Strings Are Close (1657) Another interesting String + Frequency Analysis problem from LeetCode! 🔹 Problem: Two strings are considered close if we can transform one into the other using: 1️⃣ Swap any two characters (rearranging characters). 2️⃣ Transform all occurrences of one character into another existing character and vice versa. We need to determine whether word1 can be converted into word2 using these operations. 💡 Key Insights: To make two strings close, three conditions must hold: ✔️ Both strings must have the same length. ✔️ Both strings must contain the same set of characters. ✔️ The frequency distribution of characters must match after sorting. Why? Because operation 2 allows us to swap character frequencies between existing characters. 💻 Java Solution: import java.util.*; class Solution { public boolean closeStrings(String word1, String word2) { if(word1.length() != word2.length()) return false; int[] freq1 = new int[26]; int[] freq2 = new int[26]; for(char c : word1.toCharArray()) freq1[c - 'a']++; for(char c : word2.toCharArray()) freq2[c - 'a']++; for(int i = 0; i < 26; i++){ if((freq1[i] == 0 && freq2[i] != 0) || (freq1[i] != 0 && freq2[i] == 0)) return false; } Arrays.sort(freq1); Arrays.sort(freq2); return Arrays.equals(freq1, freq2); } } 📊 Complexity Analysis: ⏱ Time Complexity: O(n) 📦 Space Complexity: O(1) Problems like this help strengthen understanding of hashing, frequency counting, and string manipulation, which are common in coding interviews. #LeetCode #DSA #Java #CodingPractice #Algorithms #ProblemSolving #SoftwareEngineering
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
-
-
🚀 DSA Series: Merge Sort Explained Simply Merge Sort is a Divide and Conquer sorting algorithm. It works by dividing the array into smaller parts, sorting them, and then merging them back together. 🧠 Idea: 1️⃣ Divide the array into two halves 2️⃣ Sort both halves recursively 3️⃣ Merge the sorted halves 💻 Java Code class Solution { void merge(int arr[], int l, int mid, int r) { int n1 = mid - l + 1; int n2 = r - mid; int left[] = new int[n1]; int right[] = new int[n2]; for(int i = 0; i < n1; i++) left[i] = arr[l + i]; for(int j = 0; j < n2; j++) right[j] = arr[mid + 1 + j]; int i = 0, j = 0, k = l; while(i < n1 && j < n2) { if(left[i] <= right[j]) { arr[k] = left[i]; i++; } else { arr[k] = right[j]; j++; } k++; } while(i < n1) { arr[k] = left[i]; i++; k++; } while(j < n2) { arr[k] = right[j]; j++; k++; } } void mergeSort(int arr[], int l, int r) { if(l < r) { int mid = (l + r) / 2; mergeSort(arr, l, mid); mergeSort(arr, mid + 1, r); merge(arr, l, mid, r); } } } 📊 Time Complexity Best Case: O(n log n) Average Case: O(n log n) Worst Case: O(n log n) 📌 Space Complexity: O(n) 💡 Key Point: Merge Sort is stable and guarantees O(n log n) performance, but it requires extra memory. #DSA #Java #MergeSort #SortingAlgorithms #CodingInterview #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀Day - 24 | Day - 8: Deep Dive into Linked Lists! Today, my DSA journey took me beyond the basics of Arrays and into the flexible world of Linked Lists. While Arrays are great, I quickly realized they have their limits—specifically when it comes to memory and efficiency. 📉 The "Array" Problem Arrays require contiguous memory, which can be a pain to allocate for large datasets. Plus, inserting or deleting elements is expensive because you have to shift everything else around. 💡 The Solution: Linked Lists A Linked List is a collection of Nodes. Each node is like a small container with two parts: Data: The actual value you want to store. Next (Address): A pointer/reference to the next node in the sequence. The list starts with a Head and ends when a node points to Null. No more shifting elements! Just update the pointers, and you're good to go. 🛠️ What I Built Today I moved from theory to implementation using Java. Here’s a snapshot of what I practiced: Structure: Defined the Node using Classes and Objects. Traversal: Mastered the while loop to navigate the list (since we don't have indexes like Arrays). Core Operations: Adding elements (at the beginning, end, and specific indexes). Removing elements (first and last). Printing the entire list. 🧠 Key Takeaway If you need fast insertions and deletions without worrying about pre-allocating memory blocks, Linked Lists are best. A big thanks to Poovizhi Mam for the clear explanation and hands-on coding practice✨ #DSA #CodingJourney #Java #DataStructures #LinkedList #LearningInPublic #SoftwareEngineering
To view or add a comment, sign in
-
-
Ever wondered why this prints true 🤔 Integer x = 125; Integer y = 125; System.out.println(x == y); // true But this prints false 😮 Integer x = 250; Integer y = 250; System.out.println(x == y); // false Looks the same… but behaves differently? Let’s break it 👇 The Reason: Integer Caching Java internally caches Integer values in the range -128 to 127. So when you write: Integer x = 125; Integer y = 125; 👉 It actually uses: Integer.valueOf(125); ✔ Both variables point to the same cached object ✔ That’s why → x == y is true ⚠️ But outside the range… Integer x = 250; Integer y = 250; ❌ No caching here ❌ Separate objects are created 👉 So → x == y is false 🚨 Important Twist (Most people miss this!) Integer x = new Integer(125); Integer y = new Integer(125); System.out.println(x == y); // false ❌ new Integer() always creates a new object ❌ Caching is NOT used here 👉 Integer caching works only with: ✔ Integer.valueOf() ✔ Autoboxing (Integer x = 125) 💡 Golden Rule x.equals(y) // ✔ Always use this for value comparison Small concepts like these can make or break your interview. Did you already know this or learned something new today? 👇 #Java #Programming #JavaTips #Coding #Developers #InterviewPrep #BackendDevelopment Inspired by amazing learning content from CoderArmy, Rohit Negi and Aditya Tandon — highly recommend following their new JAVA series!
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