📌 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
Optimized Prime Number Check in Java with O(sqrt(n)) Complexity
More Relevant Posts
-
🚀 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 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
-
-
Leveling up my searching algorithms! Today’s Java DSA topic: Binary Search. After exploring the brute-force nature of Linear Search, moving to Binary Search. Instead of checking every single element one by one O(n), Binary Search slashes the time complexity to O(log n). The catch? The array must be sorted first! (Good thing I just covered sorting algorithms). The logic is brilliant and incredibly efficient: 1. Find the middle element. 2. If it matches the target, you're done! 3. If the target is smaller, discard the right half. If larger, discard the left. 4. Repeat. #DSA #Java #BinarySearch
To view or add a comment, sign in
-
-
🚀 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
-
-
📚 Sorting Algorithms in Java – Complete Deep Dive 🚀 I completed a detailed exploration of Sorting Algorithms, focusing on how different approaches organize data efficiently and how their internal logic impacts performance and scalability. 🔹 Bubble Sort – Basic comparison-based sorting 🔹 Selection Sort – Selecting minimum elements step by step 🔹 Insertion Sort – Building a sorted portion incrementally 🔹 Quick Sort – Efficient partition-based sorting 🔹 Merge Sort – Divide & Conquer sorting technique 🔹 Bucket Sort – Distribution-based sorting approach 🔹 Cocktail Sort – Bidirectional variation of Bubble Sort 🔹 Radix Sort – Non-comparative digit-based sorting 🔹 Comb Sort – Improved Bubble Sort using gap strategy 🔹 Counting Sort – Non-comparative counting-based sorting 🔹 Shell Sort – Gap-based optimization of Insertion Sort 🔹 Cycle Sort – Minimizing memory writes during sorting 🔹 Bitonic Sort – Parallel sorting approach used in specialized systems 🔹 Tim Sort – Hybrid sorting used in modern systems 💡 Key Takeaways: • Different sorting algorithms optimize different constraints • Divide & Conquer strategies significantly improve performance • Distribution sorting removes comparison overhead in certain cases • Stability, memory usage, and complexity influence algorithm choice • Understanding sorting deeply strengthens problem-solving ability Strong algorithmic fundamentals build the foundation for efficient systems, better coding interviews, and scalable software design. 💪 #Java #DSA #SortingAlgorithms #Algorithms #JavaDeveloper #BackendDevelopment #ProblemSolving #InterviewPreparation #CodingJourney #FridayLearning #CodesInTransit
To view or add a comment, sign in
-
Refactoring for Clarity: Array Manipulation in Java 👨💻 I’ve just finished a practical exercise on array manipulation. While the goal was simple (summing two arrays), I used it as an opportunity to apply improvements. - Method decomposition: Separated concerns into specialized methods (Read, Calculate, Display). - Input validation: Built a robust loop to handle invalid inputs and prevent crashes. - Data Formatting: Used printf to create a clear, readable results table. Small improvements in logic and organization make a huge difference in software quality. #Java #Algorithms #CleanCode #Backend #LearningToCode
To view or add a comment, sign in
-
-
🔥 Turning logic into performance! 🔥 Just cracked the Two Sum problem using the Two Pointer approach in Java — and the results are super satisfying 👇 ⚡ Runtime: 2 ms (Beats 96.34%) ⚡ Memory: Optimized & efficient ⚡ Approach: Clean, scalable, and interview-ready 💡 What made the difference? Instead of going with brute force, I leveraged the power of pattern recognition and applied the two-pointer technique on a sorted array — reducing complexity and boosting performance 🚀 🧠 Key Takeaways: ✨ Patterns > Memorization ✨ Optimization matters ✨ Writing clean code is a superpower ✨ Every problem is an opportunity to think deeper 📈 Slowly but surely, leveling up my DSA skills and building a strong problem-solving mindset. Consistency + Curiosity = Growth 💯 Let’s keep pushing limits 💪 #Java #DSA #LeetCode #CodingJourney #ProblemSolving #100DaysOfCode #Tech #Learning #Developers
To view or add a comment, sign in
-
-
Tackling the "Silent Overflow" in Java 🛑🔢 I recently worked through LeetCode #7: Reverse Integer, and it was a fantastic deep dive into how Java handles 32-bit integer limits and the dangers of "silent overflows." The Problem: Reverse the digits of a signed 32-bit integer. If the reversed number goes outside the 32-bit signed range of [-2^{31}, 2^{31} - 1], the function must return 0 The "Asymmetry" Challenge: In Java, Integer.MIN_VALUE is -2,147,483,648, while Integer.MAX_VALUE is 2,147,483,647. The negative range is one unit larger than the positive range due to Two's Complement arithmetic. This creates a massive trap: using Math.abs() on the minimum value will actually overflow and remain negative! My Optimized Solution Strategy: I implemented a two-pronged approach to handle these edge cases efficiently: 1️⃣ Pre-emptive Boundary Filtering: I added a specific optimization check at the very beginning: if(x >= Integer.MAX_VALUE - 4 || x <= Integer.MIN_VALUE + 6) return 0;. This catches values at the extreme ends of the 32-bit range immediately, neutralizing potential Math.abs overflow before the main logic even begins. 2️⃣ 64-bit Buffering: I used a long data type for the reversal calculation. This provides a 64-bit "safety net," allowing the math to complete so I can verify if the result fits back into a 32-bit int boundary. Complexity Analysis: 🚀 Time Complexity: O(log_10(n))— The loop runs once for every digit in the input (at most 10 iterations for any 32-bit integer). 💾 Space Complexity: O(1)— We use a constant amount of extra memory regardless of the input size. Small details like bit-range asymmetry can break an entire application if ignored. This was a great reminder that as developers, we must always think about the physical limits of our data types! #Java #LeetCode #SoftwareDevelopment #ProblemSolving #Algorithms #CleanCode #JavaProgramming #DataStructures #CodingLife
To view or add a comment, sign in
-
-
🚀 #Headline: Day 10 — How Arrays Work in Java (Deep Dive into Memory) After learning array syntax in Part 1, today's lecture went beneath the surface. This wasn't about writing more code – it was about understanding what actually happens inside the JVM when you write new int[5]. This is the kind of knowledge that separates surface-level coders from developers who truly understand their tools. Covered in this lecture: ✔️ Why arrays are stored in contiguous memory ✔️ How arrays are allocated in Heap memory (not Stack!) ✔️ Stack vs Heap – what goes where ✔️ What happens inside the JVM during array creation ✔️ How memory indexing actually works (base address + offset) ✔️ Why array access is O(1) – constant time random access ✔️ Performance implications of contiguous storage ✔️ Special case of boolean arrays ✔️ How 2D arrays are stored in memory ✔️ Array of Strings – reference behavior The "aha" moment came when the instructor explained the math behind indexing: address = base + (index × size). This is why arrays are so fast – no traversal needed, just a direct calculation. Understanding that array references live on the Stack while the actual data lives on the Heap clarifies so many concepts about memory management. This lecture truly delivered on its promise: "This is not just coding. This is internal understanding." Learning from: 👨🏫 Aditya Tandon (Instructor) 🚀 Rohit Negi (CoderArmy) 📺 Source: https://lnkd.in/gpFpcpDs Let's connect 🤝 Pankaj Kumar #Java #100DaysOfCode #ProgrammingJourney #JavaBasics #BuildInPublic
To view or add a comment, sign in
-
-
🚀 Day 19/30 – Java DSA Challenge 🔎 Problem 74: 206. Reverse Linked List (LeetCode – Easy) Today’s problem covered one of the most fundamental operations in Linked List data structures — reversing a singly linked list. Even though it is categorized as an Easy problem, it is one of the most frequently asked interview questions and builds strong foundations for working with pointers and node manipulation. 🧠 Problem Summary You are given the head of a singly linked list. 🎯 Goal: Reverse the linked list and return the new head. Example: Input: 1 → 2 → 3 → 4 → 5 Output: 5 → 4 → 3 → 2 → 1 💡 Key Insight To reverse a linked list, we need to change the direction of each node’s next pointer. We maintain three references during traversal: prev → stores the previous node head → current node being processed nextNode → temporarily stores the next node By updating pointers step by step, we reverse the entire list without using extra space. 🔄 Approach Used 1️⃣ Initialize prev as null 2️⃣ Traverse the linked list 3️⃣ Store next node temporarily 4️⃣ Reverse the current node’s pointer 5️⃣ Move prev and head forward 6️⃣ Continue until the list ends Finally, prev becomes the new head of the reversed list. ⏱ Complexity Analysis Time Complexity: O(n) — Each node is visited exactly once. Space Complexity: O(1) — No additional memory is used. 📌 Concepts Reinforced ✔ Linked List traversal ✔ Pointer manipulation ✔ In-place data structure modification ✔ Iterative linked list algorithms 📈 Day 19 Progress Update ✅ 74 Problems Solved in my 30 Days DSA Challenge Every day I’m strengthening my understanding of data structures, algorithm patterns, and efficient problem-solving. Consistency is turning practice into real progress 🚀 #Day19 #30DaysOfDSA #Java #LeetCode #LinkedList #DataStructures #ProblemSolving #CodingJourney #InterviewPreparation
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