#Coding1 Q: Find the Largest Element in an Array (Java) Today I revised one of the most basic yet important problems in Data Structures: Problem: Find the largest element in an array Example: int[] arr = {1, 34, 56, 78, 90}; I explored 5 different approaches in Java: ✅ 1. Linear Scan (O(n) – Best for interviews) int max = arr[0]; for(int i = 1; i < arr.length; i++) { if(arr[i] > max) max = arr[i]; } ✅ 2. Using Sorting (O(n log n)) Arrays.sort(arr); int max = arr[arr.length - 1]; ✅ 3. Using Java Streams (Functional approach) int max = Arrays.stream(arr).max().getAsInt(); ✅ 4. Using Priority Queue (Max Heap) PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder()); for(int num : arr) { pq.add(num); } int max = pq.peek(); ✅ 5. Divide & Conquer (Recursive) static int findMax(int[] arr, int l, int r) { if(l == r) return arr[l]; int mid = (l + r) / 2; return Math.max(findMax(arr, l, mid), findMax(arr, mid + 1, r)); } Key Learning: Although multiple approaches exist, Linear Scan is the most efficient and interview-preferred solution with O(n) time and O(1) space. Consistent practice of fundamentals builds strong problem-solving skills More DSA posts coming soon. #DSA #Java #ProblemSolving #Coding #LinkedInLearning #SoftwareEngineering #Placements #InterviewPrep #LearningInPublic
Find Largest Element in Array: Java Solutions and Interview Prep
More Relevant Posts
-
📌 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
-
-
Hi Developers 👩💻 Let’s revisit Arrays! Arrays are one of the most fundamental data structures — and yet, they keep surprising us! Arrays are one of the most fundamental concepts in Java. If you master arrays, you unlock the foundation for advanced data structures like lists, stacks, queues, and more. 1️⃣ What is an Array? An array is a container object that holds a fixed number of values of a single data type. 🔹 Why are Arrays Important? ✔ Store multiple values in a single variable ✔ Improve code organization ✔ Essential for algorithms & problem-solving 2️⃣ How to Declare & Initialize Arrays? ✅ Method 1: Declaration + Initialization int[] numbers = {10, 20, 30, 40, 50}; ✅ Method 2: Using new keyword int[] numbers = new int[5]; numbers[0] = 10; numbers[1] = 20; 3️⃣ Types of Arrays in Java ✔ One-Dimensional Array ✔ Two-Dimensional Array (Matrix) ✔ Multi-Dimensional Array 4️⃣ Important Array Properties 📌 Index starts from 0 📌 Fixed size (cannot change after creation) 📌 Stores similar data types only 📌 Stored in contiguous memory 5️⃣ Time Complexity (Interview Focus 🔥) ✔ Access element → O(1) ✔ Update element → O(1) ✔ Search element → O(n) ✔ Insert/Delete (middle) → O(n) 6️⃣ Common Mistakes ❌ ArrayIndexOutOfBoundsException ❌ Confusing length with last index ❌ Trying to resize an array 🔹 Example: public class Main { public static void main(String[] args) { int[] numbers = {10, 20, 30, 40, 50}; for(int i = 0; i < numbers.length; i++) { System.out.println(numbers[i]); } } } 💡 Interview Insight: Arrays have fixed size. Index starts from 0. Access time complexity: O(1). 💡 Pro Tip If you need a dynamic size array, use: ➡ ArrayList (from Java Collections Framework) Mastering arrays is the first step toward becoming confident in DSA and cracking coding interviews 🔥 #Java #Programming #Coding #DSA #SoftwareDevelopment #LearningJourney
To view or add a comment, sign in
-
-
Over the last 7 days, I focused on strengthening my core Java problem-solving skills. Instead of solving random problems, I followed a structured plan covering numbers, recursion, arrays, and strings. Here’s what I practiced: Day 1–2: Number logic and recursion * Reverse number * Palindrome number * Sum of digits * Fibonacci (iterative & recursive) * Factorial (iterative & recursive) * Armstrong number * Sum of digits until single digit Day 3: Prime and special numbers * Check prime number * Print prime numbers in a range * Strong number Day 4–5: Array fundamentals * Bubble sort * Maximum and second largest element * Reverse an array * Insert element at end and at position * Remove duplicates (two-pointer technique) * Left and right rotations * Left rotate by K Day 6–7: String problems * Reverse string * Palindrome string * Count vowels * Character frequency * Anagram check * First non-repeating character * Check unique characters * Reverse each word in a sentence Key learnings: * Improved logical thinking * Better understanding of time and space complexity * Clear difference between brute force and optimized solutions * Stronger foundation for technical interviews Instead of solving 200 random questions, I focused on mastering around 30 core problems deeply. #Java #CodingPractice #ProblemSolving #InterviewPreparation #SoftwareDeveloper
To view or add a comment, sign in
-
🚀 Day 56 Out of #365DaysOfCode Github Link: https://lnkd.in/gGUy_MKZ Today I solved an interesting problem sort an integer array based on the number of 1’s in its binary representation. If two numbers have the same number of set bits, sort them in ascending numerical order. 🔎 Key Concept: Use Integer.bitCount() to count the number of 1’s. Apply a custom comparator with Arrays.sort(). Handle tie-breaking by normal ascending comparison. 💡 This problem is a great reminder of how powerful Java’s built-in methods and custom comparators can be for writing clean and efficient solutions. Time Complexity: O(n log n) It’s always exciting to explore bit manipulation problems—they strengthen logical thinking and deepen understanding of how numbers work internally. #Java #Coding #DataStructures #Algorithms #BitManipulation #ProblemSolving #Learning
To view or add a comment, sign in
-
-
🚀 Prefix Sum — Answer Range Queries in O(1) While practicing DSA, I revisited one of the simplest yet most powerful techniques — Prefix Sum. 👉 It helps compute range sums efficiently after one preprocessing pass. --- 💡 What is Prefix Sum? A prefix sum array stores the cumulative sum up to each index. Formula: prefix[i] = prefix[i-1] + arr[i] --- 📌 Example Input Array: arr = [2, 4, 6, 8, 10] Prefix Array becomes: prefix = [2, 6, 12, 20, 30] --- 🎯 Range Sum Query (L = 1, R = 3) Instead of looping every time: sum(L, R) = prefix[R] − prefix[L−1] = 20 − 2 = 18 ⚡ Preprocessing → O(n) ⚡ Each query → O(1) --- 🔥 Where is it useful? ✅ Range sum queries ✅ Subarray sum problems ✅ Count subarrays with given sum ✅ 2D prefix sum problems ✅ Competitive programming --- 💻 Java Implementation int[] prefix = new int[n]; prefix[0] = arr[0]; for(int i = 1; i < n; i++){ prefix[i] = prefix[i-1] + arr[i]; } // range sum from L to R int rangeSum = prefix[R] - (L > 0 ? prefix[L-1] : 0); --- ✨ Preprocess once, answer many queries fast! #DSA #PrefixSum #Coding #Java #CompetitiveProgramming #WomenInTech
To view or add a comment, sign in
-
-
Leetcode problem No : 345 🚀 Mastering Two-Pointer Technique in Java — Reverse Vowels Problem Today I practiced a classic two-pointer algorithm by solving the “Reverse Vowels of a String” problem in Java. The core idea is simple but powerful: 👉 Use two indices — one from the start and one from the end — and move them toward each other while swapping only the target characters (vowels in this case). 💡 Key Learning Points: ✅ How to convert a string into a mutable character array ✅ Efficient character checking using a helper function (isVowel) ✅ Optimized time complexity O(n) with constant extra space ✅ Clean pointer movement logic to avoid unnecessary operations This approach is widely used in: String manipulation problems Array partitioning Palindrome checks Competitive programming & coding interviews Practicing these patterns consistently builds strong problem-solving intuition. Small problems like this create the foundation for solving much harder algorithm challenges later. If you’re learning Data Structures & Algorithms, remember: Consistency beats complexity. Solve daily, even if it’s small. 🔥 What was the last algorithm pattern you practiced? #Java #DSA #CodingInterview #TwoPointer #Programming #SoftwareEngineering #LeetCode #ProblemSolving #Developers #CodingJourney #TechCareer
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
-
-
Merge Sort in Java may look complex, but most mistakes happen because: • we don’t clearly understand how the array is divided • we mix up the merge logic • we forget that sorting actually happens during the merge step The core idea is straightforward: divide the array into smaller parts, sort them recursively, and then merge them back in sorted order. What really happens: – The array is repeatedly divided until each part has one element – A single element is already sorted by definition – Then, pairs of sorted subarrays are merged to form bigger sorted arrays So: – First, size-1 arrays are merged into size-2 sorted arrays – Then size-2 into size-4 – Then size-4 into size-8 – And so on, until the whole array is sorted The key insight: 👉 All the real sorting happens during merging, not during splitting. Once you understand that: • recursion just breaks the problem into smaller pieces • merge logic ensures order • time complexity stays O(n log n) in all cases Merge Sort isn’t about simplicity — it’s about guaranteed performance and clean divide-and-conquer thinking. That’s what makes it a foundation algorithm for: ✔ large datasets ✔ external sorting ✔ stable sorting requirements #Java #MergeSort #DSA #Algorithms #DivideAndConquer #ProblemSolving #BackendEngineering
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
-
-
Day 42 of My DSA Journey 🚀 | Basic String Operations in Java 🧠 Summary: Demonstrate common string operations in Java such as comparison, length calculation, substring extraction, case conversion, and character traversal. 💡 Key Concepts: • String immutability • == vs .equals() comparison • Case-insensitive comparison • Built-in string methods • Character iteration 🧠 Approach: This program explores several commonly used String methods. Step-by-step operations: • Declaration Two ways to create strings: → Using string literal → Using the new keyword • String Comparison → == checks if two references point to the same object. → .equals() compares actual string values. → .equalsIgnoreCase() compares values ignoring case differences. • String Methods → length() returns number of characters. → charAt(index) retrieves character at given position. → substring(start,end) extracts part of a string. → toUpperCase() converts characters to uppercase. → toLowerCase() converts characters to lowercase. → contains() checks if a substring exists. • String Traversal → Iterate through the string using a loop and access characters using charAt(). 🔧 Practical Usage / Why This Matters: • Processing user input in applications • Validating text-based data • Parsing messages or logs • Formatting and transforming text data 🌱 What I Learned Today: I strengthened my understanding of Java String methods and how object comparison differs from value comparison. 🙌 If you're preparing for placements, let’s connect and grow together! #dsa #datastructures #algorithms #java #javadeveloper #javaprogramming #dsainjava #strings #stringalgorithms #codinginterview #leetcode #geekforgeeks #codingpractice #interviewpreparation #100daysofcode #developerjourney #softwaredeveloper #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