☕ DSA Using Java – Stack Data Structure Explained The Stack is one of the most fundamental data structures in Data Structures & Algorithms (DSA). It follows the principle of: 👉 LIFO (Last In, First Out) This means the last element inserted into the stack is the first one to be removed. 🔹 What is a Stack? A stack allows operations only at one end, called the top. It supports controlled data access: Only the last inserted element can be accessed or removed. Push and Pop operations are tightly connected. Think of it like a stack of plates — you can only remove the top plate first. 🔹 Basic Stack Operations 1️⃣ Push Adds an element to the top of the stack. If the stack is full → Error is shown. 2️⃣ Pop Removes the top element from the stack. Top index is decremented after removal. 3️⃣ Peek Returns the top element without removing it. 4️⃣ isFull Checks whether the stack is full. 5️⃣ isEmpty Checks whether the stack is empty. 🔹 Stack Implementation in Java A stack can be implemented using: An array A top variable (initialized to -1) Example logic: Push: intArray[++top] = data; Pop: return intArray[top--]; The demo program (StackDemo.java) creates a stack of size 10 and performs push operations: stack.push(3); stack.push(5); stack.push(9); stack.push(1); stack.push(12); stack.push(15); 🔹 Output Element at top of the stack: 15 Elements: 15 12 1 9 5 3 Stack full: false Stack empty: true This clearly demonstrates the LIFO behavior — 15 (last inserted) is removed first. 💡 Mastering Stack is essential for solving problems related to: Expression evaluation Parenthesis checking Backtracking Undo/Redo functionality Recursive algorithms Strong DSA fundamentals = Strong Java developer 🚀 #Java #DSA #Stack #DataStructures #Algorithms #JavaProgramming #CodingInterview #FullStackJava #AshokIT
Java Stack Data Structure Explained with LIFO Principle
More Relevant Posts
-
I build my own Stack data structure in Java (Array + LinkedList implementation) I did'nt just added simple (push/pop) operations, i actually implemented some decent methods in both implementations. I overrode the toString() method so that whenever the object reference is printed, it displays the stack’s contents instead of the default memory address representation. When building using Array the most important concept i learned is dynamic resizing. 🔹 Array-based Dynamic Stack: Generic implementation (Stack<T>) Dynamic resizing (capacity doubles when full) push, pop, peek, search trimToSize() for memory optimization reverse() using two-pointer technique swapTop() utility method clone() for deep copy pushAll() with varargs & collections popMultiple() for batch operations 🔹 Linked List-based Stack Generic stack with Comparable support Efficient push / pop using head pointer contains() search operation toArray() conversion clone() while preserving order sort() functionality using Collections.sort() Batch operations like pushAll() and pop(k) 💡 Key concepts practiced Generics in Java Dynamic memory management Custom exception handling Linked list node design Time complexity considerations (O(1) push/pop) Designing reusable APIs This exercise helped me understand how real data structures work internally, instead of just using library implementations. View comment section for the code on github. Next, I'm planning to implement: Queue (Array + Linked List) Deque Iterator support for custom data structures Always open to feedback, suggestions, or improvements from experienced developers. #Java #DataStructures #DSA #ComputerScience #SoftwareEngineering #LearningInPublic #JavaDeveloper
To view or add a comment, sign in
-
Vector embeddings are the secret sauce that transforms how Java applications understand and process unstructured data. At its core, an embedding converts text, code, or any data into a numerical vector representation that captures semantic meaning. When you feed "Spring Boot tutorial" into an embedding model, you get something like a 768-dimensional array where each number represents different aspects of meaning. Similar concepts cluster together in this vector space, making "Spring Boot guide" numerically closer than "Python Flask tutorial." For Java developers, this changes everything about search, recommendation systems, and AI integration. Instead of relying on exact keyword matches or complex SQL queries, your applications can understand context and similarity. A user searching for "dependency injection" would also find relevant results about "IoC containers" because their embeddings are mathematically similar. Building this into Spring Boot applications is straightforward with libraries like LangChain4j or direct integration with OpenAI's text-embedding-ada-002 model. I've seen teams replace entire Elasticsearch implementations with vector similarity searches that deliver more relevant results with less configuration. The real power emerges when you store these embeddings in vector databases like Pinecone or Chroma, enabling millisecond similarity searches across millions of documents. This becomes the foundation for RAG systems where your Java application can intelligently retrieve relevant context before generating responses. The learning curve is gentle for Java developers because it follows familiar patterns - you're still making HTTP calls to embedding APIs and storing numerical data, just with a new understanding of what those numbers represent. How are you currently handling search and content discovery in your Java applications, and where do you see the biggest opportunities for semantic understanding? #AI #Java #SpringBoot #SoftwareArchitecture #MachineLearning #LLM #TechLeadership #AIStrategy #GenerativeAI #SystemDesign #JavaDeveloper #AIAdoption
To view or add a comment, sign in
-
🔎 Small concept. Big impact in backend systems: Regex (Regular Expressions) While building backend APIs using Spring Boot, I realized how important input validation is for maintaining data quality and application reliability. One powerful tool developers use for this is Regex (Regular Expressions). 📌 What is Regex? Regex is a pattern-matching technique used to validate, search, and process text. It allows applications to ensure that incoming data follows a specific format before it reaches the database. 📌 Example: Email Validation Java Copy code String regex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$"; boolean valid = Pattern.matches(regex, email); This pattern checks whether the input follows a valid email format. 📌 Where Regex is commonly used • Email validation • Password strength rules • Phone number formatting • Input validation in APIs • Log data extraction In backend systems built with Spring Boot, Regex is often used along with validation annotations like @Pattern to ensure clean and secure input data. Understanding small concepts like Regex helps build more reliable and scalable backend systems. Hashtags (good reach mix) Use 10–15 hashtags only. #Java #SpringBoot #BackendDevelopment #SoftwareEngineering #Programming #Developers #JavaDeveloper #Regex #APIDesign #SystemDesign #Coding #SoftwareDevelopment #TechCommunity #CleanCode #CodingJourney
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
-
-
How HashMap Works Internally (Hashing, Collision) — Simple Explanation: HashMap is one of the most commonly used data structures in Java, but understanding what happens internally makes it much more interesting. Think of a HashMap like an apartment building. Each apartment number represents a bucket index in an internal array. Step 1: Hashing When inserting a key-value pair: map.put("apple", 10) Java first calculates a hash code of the key. This hash code is converted into an array index where the data should be stored. Example: hash("apple") → 7 So the value is stored in bucket 7. This process is called hashing - converting a key into a location in the array. Step 2: Collision But different keys can sometimes produce the same bucket index. Example: hash("apple") → 7 hash("grape") → 7 Now two keys want to occupy the same bucket. This situation is called a collision. Collisions in a HashMap are handled using separate chaining (linked lists or trees) or open addressing techniques like linear probing, quadratic probing, or double hashing Step 3: How LinkedList Solves Collision Instead of overwriting the existing value, HashMap stores multiple entries in that bucket using a LinkedList. So bucket 7 looks like this: Bucket 7 [apple,10] → [grape,20] → [mango,15] Each element points to the next one, forming a chain. When retrieving a value: map.get("grape") HashMap: 1. Computes the bucket index using hashing 2. Goes to bucket 7 3. Traverses the linked list 4. Finds the matching key Why HashMap is Fast On average: Time Complexity → O(1) Because hashing allows direct bucket access. Only when collisions occur does it traverse the chain. Understanding how fundamental data structures work internally helps write better and more efficient code. #Java #DataStructures #HashMap #Algorithms #SoftwareEngineering #Coding
To view or add a comment, sign in
-
🚀 DSA Journey Update: ArrayList Mastered. ✅ I’ve completed ArrayList (Java Collections) — a crucial step in understanding dynamic data handling and efficient data manipulation. This phase strengthened my understanding of how data can be stored, accessed, and optimised in real-world applications. Instead of static arrays, I explored how dynamic structures improve flexibility and performance. ✅ ArrayList Concepts Practised • Dynamic resizing & memory behavior • CRUD operations & traversal techniques • Sorting & searching operations • 2D ArrayLists & matrix-like structures • Efficient element swapping & reverse traversal • Using ArrayLists in algorithmic problems 🧩 Problems & Patterns Explored: • Finding maximum & reverse traversal • Pair Sum (Brute Force vs Two-Pointer Optimisation) • Container With Most Water problem • Sorted & Rotated array pair detection • Multidimensional ArrayList construction Working with ArrayLists helped me understand the transition from basic storage structures to efficient algorithmic solutions. 🔥 What’s Next? → Linked List Data Structure Now moving into Linked Lists, focusing on: • Dynamic node-based memory structure • Insertions & deletions efficiency • Singly & Doubly Linked Lists • Reversal & cycle detection • Real-world use cases & performance tradeoffs Excited to continue building consistency and strengthening problem-solving skills. 📢 What’s Next? Linked List Data Structure. 💬 Which data structure changed the way you think about memory and efficiency? For references, visit my GitHub repository: https://lnkd.in/ge-yVhyS Visit Links: https://lnkd.in/gG-rt7tj https://satinderpoetry.com I’m sharing this to stay consistent and connect with others on the same learning path. #DSA #Java #ArrayList #LinkedList #DataStructures #Algorithms #ProblemSolving #CodingJourney #LearningByDoing #SatinderLearns_DSA
To view or add a comment, sign in
-
-
Building a Refactoring Agent? You need more than LLMs to handle HQL safely. If you’re building AI agents for legacy Java code, treating database queries as raw strings is asking for trouble. LLMs at times fall behind when handling rigid logic required to safely rename entities or migrate joins without a formal grammar. That’s why I built hql-parser: a standalone Java library that gives AI agents a structural "brain" for HQL and JPQL. The Solution: This library provides the semantic layer that prompt engineering alone lacks. It deconstructs queries into structured metadata, exposing: Entities & Fields: No more "hallucinated" mapping. Aliases & Joins: Clear visibility into relational dependencies. PostgreSQL Conversion: Direct transformation for modernizing data layers. Why it matters for Agentic Workflows: By converting HQL into a structured AST, automated refactoring becomes predictable. This is currently the backbone of my own AI refactoring agent, enabling complex architectural changes that require 100% accuracy. If you’re building specialized AI agents, migration tools, or static analysis engines for the Java ecosystem, check it out. Explore the source on GitHub: https://lnkd.in/gMy5-UZE #Java #GenerativeAI #LLMs #Hibernate #PostgreSQL #Refactoring #AIProgramming #OpenSource
To view or add a comment, sign in
-
🚀 𝐄𝐕𝐎𝐋𝐔𝐓𝐈𝐎𝐍 𝐎𝐅 𝐓𝐈𝐓𝐀𝐍: 𝐒𝐨𝐥𝐯𝐢𝐧𝐠 𝐃𝐢𝐬𝐭𝐫𝐢𝐛𝐮𝐭𝐞𝐝 𝐒𝐭𝐚𝐭𝐞 & 𝐈𝐧𝐭𝐞𝐠𝐫𝐚𝐭𝐢𝐧𝐠 𝐃𝐚𝐠𝐬𝐭𝐞𝐫 Building 𝐓𝐢𝐭𝐚𝐧 (my custom Java-based distributed orchestrator) from scratch has been a massive learning curve. In my last update, I got dynamic scaling and agentic execution working, but as Titan’s compute capabilities expanded, I ran into a 𝑐𝑙𝑎𝑠𝑠𝑖𝑐 𝑑𝑖𝑠𝑡𝑟𝑖𝑏𝑢𝑡𝑒𝑑 𝑠𝑦𝑠𝑡𝑒𝑚𝑠 𝑤𝑎𝑙𝑙: 𝐒𝐭𝐚𝐭𝐞 𝐌𝐚𝐧𝐚𝐠𝐞𝐦𝐞𝐧𝐭 Without a persistence layer: • The cluster wasn’t crash-recoverable • Tasks had no clean way to share data across execution steps • Inter-step communication relied on logs or shared folders 🔹 𝐓𝐈𝐓𝐀𝐍𝐒𝐓𝐎𝐑𝐄: 𝐃𝐈𝐒𝐓𝐑𝐈𝐁𝐔𝐓𝐄𝐃 𝐊/𝐕 𝐃𝐀𝐓𝐀 𝐁𝐔𝐒 Last year, I built 𝐑𝐞𝐝𝐢𝐬𝐉𝐚𝐯𝐚, a minimal multithreaded Redis clone using the RESP protocol as a learning exercise. I’ve now integrated it directly into Titan via an 𝐀𝐝𝐚𝐩𝐭𝐞𝐫 𝐏𝐚𝐭𝐭𝐞𝐫𝐧. TitanStore now handles: • Inter-task communication across nodes • Append-Only File (AOF) persistence • Crash-recoverable execution state Because the integration is adapter-based, the backend can be swapped for a real Redis instance instantly without changing user code. 🔹 𝐏𝐋𝐔𝐆𝐆𝐈𝐍𝐆 𝐈𝐍𝐓𝐎 𝐓𝐇𝐄 𝐄𝐂𝐎𝐒𝐘𝐒𝐓𝐄𝐌 (𝐃𝐀𝐆𝐒𝐓𝐄𝐑) While Titan is fully autonomous and capable of managing DAGs on its own, I wanted to validate that it could integrate cleanly with modern industry tooling. By bridging Titan with Dagster: • Dagster handles the 𝐂𝐨𝐧𝐭𝐫𝐨𝐥 𝐏𝐥𝐚𝐧𝐞 (Logical DAGs, UI, Data Lineage) • Titan operates as the 𝐑𝐮𝐧𝐭𝐢𝐦𝐞 𝐄𝐧𝐠𝐢𝐧𝐞 (Distributed compute scheduling & hardware-aware routing) The Titan Python SDK acts as a clean translation layer between the two. This effectively transforms a control-plane-only scheduler into a hardware-aware distributed execution runtime. 𝐓𝐄𝐂𝐇𝐍𝐈𝐂𝐀𝐋 𝐅𝐎𝐔𝐍𝐃𝐀𝐓𝐈𝐎𝐍 (𝐏𝐔𝐑𝐄 𝐉𝐀𝐕𝐀 𝟏𝟕) To learn the underlying primitives, the Titan core engine is built with zero external dependencies (only java) compiling down to an ultra-lightweight 74KB JAR. • 𝐒𝐭𝐨𝐫𝐚𝐠𝐞: Native RESP parsing + concurrent structures • 𝐈𝐏𝐂: Custom binary protocol for Java ↔ Python execution • 𝐏𝐫𝐨𝐜𝐞𝐬𝐬 𝐒𝐮𝐩𝐞𝐫𝐯𝐢𝐬𝐢𝐨𝐧: OS-level lifecycle management via Java 9 Process API • 𝐎𝐫𝐜𝐡𝐞𝐬𝐭𝐫𝐚𝐭𝐢𝐨𝐧: Strict Control Plane (Dagster) ↔ Data Plane (Titan) decoupling While Titan is ultimately a personal systems project, it’s designed to handle reasonable mid-scale infrastructure workloads. It currently lacks enterprise-grade security features as of now but diving this deep into the plumbing of how orchestrators actually work under the hood has been an incredible experience. 🔗 Full repo and architectural breakdown: https://lnkd.in/gxC_t5tv Dagster ↔ Titan Sequence Diagram: https://lnkd.in/gGxbDYXD #Java #DistributedSystems #Dagster #DataEngineering #SystemDesign #OpenSource
To view or add a comment, sign in
-
More from this author
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