diff --git a/README.md b/README.md index 571442c..acd7826 100644 --- a/README.md +++ b/README.md @@ -1 +1,159 @@ # java-collections +# Java Collections Framework Learning Guide + +This repository is designed to help you learn the **Java Collections Framework step-by-step**. Each section introduces a new concept, provides examples, and gives you practice problems to reinforce what you learned. + +Your goal is to **work through the folders in order**. Each folder contains: + +- **README.md** → Explanation of the concept +- **Examples / Demo Code** → Working examples to study +- **Practice Problems** → Exercises for you to complete + +Follow the steps below to complete the assignment. + +--- + +# Learning Path + +Work through the following sections **in this exact order**. + +## 1. Hierarchy + +Start by understanding the **structure of the Java Collections Framework**. + +In this section: +- Read the `README.md` +- Review the hierarchy notes +- Run the example code +- Complete the practice questions + +This section will help you understand **how everything connects together**. + +--- + +## 2. Iterable + +Next, learn about **Iterable**, the root interface of the collections framework. + +Focus on: +- How iteration works +- How enhanced for-loops work +- The role of `Iterator` + +Steps: +1. Read the README +2. Study the demo code +3. Complete the practice exercises + +--- + +## 3. Collection + +This section introduces the **Collection interface**, which is the parent of most collection types. + +Key concepts: +- Common collection methods +- Shared behavior across lists, sets, and queues + +Steps: +1. Read the README +2. Study the examples +3. Complete the practice problems + +--- + +## 4. Lists + +Lists store **ordered collections of elements** and allow duplicates. + +Structures covered include: +- ArrayList +- LinkedList +- Vector +- Stack + +Steps: +1. Read the README for each list implementation +2. Study the demo code +3. Complete the practice problems + +--- + +## 5. Sets + +Sets store **unique elements** and do not allow duplicates. + +Structures covered include: +- HashSet +- LinkedHashSet +- TreeSet + +Steps: +1. Read the README for each set implementation +2. Study the demo code +3. Complete the practice problems + +--- + +## 6. Queues + +Queues process elements in order, typically using **FIFO (First-In, First-Out)** behavior. + +Structures covered include: +- Queue +- Deque +- ArrayDeque +- PriorityQueue + +Steps: +1. Read the README for each queue structure +2. Study the demo code +3. Complete the practice problems + +--- + +## 7. Maps + +Maps store **key-value pairs**. + +Structures covered include: +- HashMap +- LinkedHashMap +- TreeMap + +Steps: +1. Read the README for each map implementation +2. Study the demo code +3. Complete the practice problems + +--- + +# Final Step: HackerRank Problems + +After completing all sections, you will solve **10 HackerRank-style problems** related to collections. + +These problems are designed to test your ability to: + +- Choose the correct data structure +- Use collections effectively +- Solve real-world coding problems + +Complete all problems in the provided Java file. + +--- + +# Tips for Success + +- Work **through the sections in order** +- Run the example code to see how each structure behaves +- Try solving practice problems **before looking up solutions** +- Focus on **understanding when to use each collection** + +By the end of this assignment, you should understand how to work with: + +- Lists +- Sets +- Queues +- Maps + +and how they fit into the **Java Collections Framework**. diff --git a/src/main/java/Collections/Practice/CollectionBasics.java b/src/main/java/Collections/Practice/CollectionBasics.java new file mode 100644 index 0000000..e45cb49 --- /dev/null +++ b/src/main/java/Collections/Practice/CollectionBasics.java @@ -0,0 +1,119 @@ +package Collections.Practice; + +import java.util.ArrayList; +import java.util.Collection; + +public class CollectionBasics { + public static void main(String[] args) { + + Collection numbers = new ArrayList<>(); + + numbers.add(4); + numbers.add(8); + numbers.add(15); + numbers.add(16); + numbers.add(23); + numbers.add(42); + + System.out.println("Sum of numbers: " + sum(numbers)); + System.out.println("Count of even numbers: " + countEven(numbers)); + System.out.println("Largest number: " + findMax(numbers)); + System.out.println("Contains duplicates? " + hasDuplicates(numbers)); + } + + + /* + PROBLEM 1 + Return the sum of all numbers in the collection + */ + public static int sum(Collection numbers) { + + int total = 0; + + // TODO: + // Loop through the collection + // Add each number to total + + return total; + } + + + /* + PROBLEM 2 + Count how many numbers are even + */ + public static int countEven(Collection numbers) { + + int count = 0; + + // TODO: + // Loop through the collection + // If the number is even, increase count + + return count; + } + + + /* + PROBLEM 3 + Find the largest number in the collection + */ + public static int findMax(Collection numbers) { + + int max = Integer.MIN_VALUE; + + // TODO: + // Loop through numbers + // Update max if current number is larger + + return max; + } + + + /* + PROBLEM 4 + Return true if the collection contains duplicates + Return false otherwise + */ + public static boolean hasDuplicates(Collection numbers) { + + // TODO: + // Hint: + // Compare the size of a collection with the size of a Set + + return false; + } + + + /* + PROBLEM 5 + Count how many times a target value appears + */ + public static int countOccurrences(Collection numbers, int target) { + + int count = 0; + + // TODO: + // Loop through numbers + // If number equals target, increase count + + return count; + } + + + /* + BONUS PROBLEM + Create and return a new collection + that only contains numbers greater than 20 + */ + public static Collection filterGreaterThanTwenty(Collection numbers) { + + Collection result = new ArrayList<>(); + + // TODO: + // Loop through numbers + // Add numbers greater than 20 to result + + return result; + } +} diff --git a/src/main/java/Collections/Practice/CommonMethodsDemo.java b/src/main/java/Collections/Practice/CommonMethodsDemo.java new file mode 100644 index 0000000..b2dd6f9 --- /dev/null +++ b/src/main/java/Collections/Practice/CommonMethodsDemo.java @@ -0,0 +1,170 @@ +package Collections.Practice; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +public class CommonMethodsDemo { + public static void main(String[] args) { + + System.out.println("=== COLLECTION COMMON METHODS DEMO ===\n"); + + /* + IMPORTANT CONCEPT: + We are using the Collection interface as the reference type. + The object type is ArrayList. + */ + + Collection fruits = new ArrayList<>(); + + // ------------------------------ + // add() + // ------------------------------ + + System.out.println("Adding elements using add()"); + + fruits.add("Apple"); + fruits.add("Banana"); + fruits.add("Orange"); + fruits.add("Mango"); + + System.out.println("Fruits: " + fruits); + + + // ------------------------------ + // size() + // ------------------------------ + + System.out.println("\nChecking size of collection"); + + int size = fruits.size(); + System.out.println("Size: " + size); + + + // ------------------------------ + // contains() + // ------------------------------ + + System.out.println("\nChecking if collection contains certain items"); + + boolean hasApple = fruits.contains("Apple"); + boolean hasGrape = fruits.contains("Grape"); + + System.out.println("Contains Apple? " + hasApple); + System.out.println("Contains Grape? " + hasGrape); + + + // ------------------------------ + // remove() + // ------------------------------ + + System.out.println("\nRemoving an element"); + + fruits.remove("Banana"); + + System.out.println("After removing Banana:"); + System.out.println(fruits); + + + // ------------------------------ + // addAll() + // ------------------------------ + + System.out.println("\nAdding multiple elements using addAll()"); + + List moreFruits = new ArrayList<>(); + moreFruits.add("Pineapple"); + moreFruits.add("Strawberry"); + moreFruits.add("Peach"); + + fruits.addAll(moreFruits); + + System.out.println("After addAll:"); + System.out.println(fruits); + + + // ------------------------------ + // Iterating through Collection + // ------------------------------ + + System.out.println("\nLooping through collection:"); + + for (String fruit : fruits) { + System.out.println(fruit); + } + + + // ------------------------------ + // isEmpty() + // ------------------------------ + + System.out.println("\nChecking if collection is empty"); + + boolean empty = fruits.isEmpty(); + System.out.println("Is empty? " + empty); + + + // ------------------------------ + // clear() + // ------------------------------ + + System.out.println("\nClearing the collection"); + + fruits.clear(); + + System.out.println("After clear:"); + System.out.println(fruits); + + + System.out.println("\nCheck if empty after clear:"); + + System.out.println("Is empty? " + fruits.isEmpty()); + + + // ------------------------------ + // TODO Exploration Section + // ------------------------------ + + /* + TODO 1: + Create a new Collection called numbers + Add the following values: + 10, 20, 30, 40, 50 + */ + + + /* + TODO 2: + Print the size of the numbers collection + */ + + + /* + TODO 3: + Check if the collection contains 30 + */ + + + /* + TODO 4: + Remove the number 20 + */ + + + /* + TODO 5: + Loop through the numbers collection + and print each value + */ + + + /* + REFLECTION QUESTIONS: + + 1. Why can we use Collection as the reference type? + 2. What methods are available because of the Collection interface? + 3. What methods are NOT available when using Collection instead of List? + */ + } + +} diff --git a/src/main/java/Collections/Quiz/KnowledgeCheck.md b/src/main/java/Collections/Quiz/KnowledgeCheck.md new file mode 100644 index 0000000..43ee11f --- /dev/null +++ b/src/main/java/Collections/Quiz/KnowledgeCheck.md @@ -0,0 +1,162 @@ +````md +# Quiz.md + +# Java Collections Framework Quiz — Collection Interface + +## Instructions +Answer the following **10 questions** about the **Java `Collection` interface** and common collection methods. +Select the **best answer** for each question. + +--- + +## Question 1 +Which of the following is **true** about the `Collection` interface? + +A. `Collection` is a class +B. `Collection` extends `List` +C. `Collection` is the root interface for most collection types +D. `Collection` only stores key-value pairs + +--- + +## Question 2 +What will the following code print? + +```java +Collection numbers = new ArrayList<>(); + +numbers.add(10); +numbers.add(20); +numbers.add(30); + +System.out.println(numbers.size()); +```` + +A. 0 +B. 1 +C. 3 +D. 30 + +--- + +## Question 3 + +Which method is used to **check if an element exists** inside a collection? + +A. `search()` +B. `exists()` +C. `contains()` +D. `check()` + +--- + +## Question 4 + +What will the following code print? + +```java +Collection names = new ArrayList<>(); + +names.add("Alex"); +names.add("Jordan"); + +names.remove("Alex"); + +System.out.println(names); +``` + +A. `[Alex, Jordan]` +B. `[Jordan]` +C. `[Alex]` +D. `[]` + +--- + +## Question 5 + +Which method adds **all elements from another collection** into an existing collection? + +A. `add()` +B. `addAll()` +C. `insertAll()` +D. `merge()` + +--- + +## Question 6 + +What will the following code print? + +```java +Collection numbers = new ArrayList<>(); + +System.out.println(numbers.isEmpty()); +``` + +A. `true` +B. `false` +C. `0` +D. Compilation error + +--- + +## Question 7 + +Which method removes **all elements** from a collection? + +A. `removeAll()` +B. `deleteAll()` +C. `clear()` +D. `reset()` + +--- + +## Question 8 + +What will the following code print? + +```java +Collection nums = new ArrayList<>(); + +nums.add(5); +nums.add(10); +nums.add(15); + +for(Integer n : nums) { + System.out.print(n + " "); +} +``` + +A. `5 10 15` +B. `15 10 5` +C. `0 1 2` +D. Compilation error + +--- + +## Question 9 + +Which of the following **cannot be guaranteed** when using the `Collection` interface? + +A. Elements can be added +B. Elements can be removed +C. Indexed access using `.get(index)` +D. Elements can be iterated using a loop + +--- + +## Question 10 + +What is the **main benefit** of writing code like this? + +```java +Collection fruits = new ArrayList<>(); +``` + +A. It automatically sorts the collection +B. It prevents duplicates +C. It allows flexibility to change implementations later +D. It forces the collection to be synchronized + +``` +``` diff --git a/src/main/java/Collections/README.md b/src/main/java/Collections/README.md new file mode 100644 index 0000000..a3dfc4f --- /dev/null +++ b/src/main/java/Collections/README.md @@ -0,0 +1,139 @@ +```markdown +# Collection + +## What Is Collection? + +`Collection` is the **core interface** of the Java Collections Framework. + +It represents a **group of objects**. + +It is the parent of: +- `List` +- `Set` +- `Queue` + +⚠ `Map` is NOT a Collection. + +--- + +## Where It Fits + +``` + +Iterable +↓ +Collection +↓ +List / Set / Queue + +```` + +Every `List`, `Set`, and `Queue` is a `Collection`. + +--- + +## What Collection Provides + +`Collection` defines common behaviors shared by all collections. + +Core methods: + +```java +collection.add(element); +collection.remove(element); +collection.contains(element); + +collection.size(); +collection.isEmpty(); +collection.clear(); + +collection.addAll(otherCollection); +collection.removeAll(otherCollection); +collection.retainAll(otherCollection); +```` + +--- + +## Looping + +Because `Collection` extends `Iterable`, you can loop through it: + +```java +for (String item : collection) { + System.out.println(item); +} +``` + +--- + +## Time Complexity + +Depends on implementation: + +| Operation | Typical Complexity | +| ------------ | ------------------ | +| `add()` | O(1) or O(n) | +| `remove()` | O(1) or O(n) | +| `contains()` | O(1) or O(n) | +| `size()` | O(1) | + +⚠ The actual complexity depends on whether it’s a `List`, `Set`, or `Queue`. + +--- + +## Collection vs List + +| Feature | Collection | List | +| ------------------- | -------------- | ---- | +| Ordered? | Not guaranteed | Yes | +| Index-based access? | No | Yes | +| Allows duplicates? | Depends | Yes | + +`Collection` does NOT support indexing. + +--- + +## Best Practice + +Use the interface as your reference type: + +```java +Collection items = new ArrayList<>(); +``` + +This allows flexibility: +You can switch to `HashSet` or `LinkedList` later without changing much code. + +--- + +## Common Mistakes + +* Thinking `Collection` supports indexing +* Assuming ordering exists +* Forgetting `Map` is separate from Collection + +--- + +## Practice Ideas + +* Write a method that accepts `Collection` and returns the sum +* Find intersection of two collections +* Remove duplicates using a Set +* Determine if one collection is a subset of another + +--- + +## Summary + +Collection = **the shared foundation for List, Set, and Queue**. + +It provides: + +* Core add/remove/search operations +* Looping capability +* Bulk operations (`addAll`, `retainAll`, etc.) + +Understanding `Collection` helps you understand what all collections have in common. + +``` +``` diff --git a/src/main/java/CollectionsHackerrank/CollectionsHackerrankProblems.java b/src/main/java/CollectionsHackerrank/CollectionsHackerrankProblems.java new file mode 100644 index 0000000..6c2f4e1 --- /dev/null +++ b/src/main/java/CollectionsHackerrank/CollectionsHackerrankProblems.java @@ -0,0 +1,178 @@ +package CollectionsHackerrank; + +import java.util.List; +import java.util.Map; +import java.util.Queue; + +public class CollectionsHackerrankProblems { + public class CollectionsHackerrankPractice { + + public static void main(String[] args) { + + // You can test your methods here + + } + + /* + Problem 1 + Remove duplicates from a list of integers. + + Example + Input: [1,2,2,3,4,4,5] + Output: [1,2,3,4,5] + */ + public static List removeDuplicates(List numbers) { + + // TODO: Implement this method + + return null; + } + + /* + Problem 2 + Count how many times each number appears. + + Example + Input: [1,2,2,3,3,3] + Output: {1=1, 2=2, 3=3} + */ + public static Map countFrequency(List numbers) { + + // TODO: Implement this method + + return null; + } + + /* + Problem 3 + Return the first number that appears only once. + + Example + Input: [4,5,1,2,0,4] + Output: 5 + */ + public static Integer firstUnique(List numbers) { + + // TODO: Implement this method + + return null; + } + + /* + Problem 4 + Return true if any two numbers add up to the target. + + Example + numbers = [2,7,11,15] + target = 9 + + Output: true + */ + public static boolean twoSum(List numbers, int target) { + + // TODO: Implement this method + + return false; + } + + /* + Problem 5 + Count how many unique words exist in a list. + + Example + Input: ["apple","banana","apple","orange"] + Output: 3 + */ + public static int countUniqueWords(List words) { + + // TODO: Implement this method + + return 0; + } + + /* + Problem 6 + Reverse a queue. + + Example + Input: [1,2,3,4] + Output: [4,3,2,1] + */ + public static Queue reverseQueue(Queue queue) { + + // TODO: Implement this method + + return null; + } + + /* + Problem 7 + Determine whether parentheses are balanced. + + Example + Input: "(())" + Output: true + + Input: "(()" + Output: false + */ + public static boolean isBalanced(String expression) { + + // TODO: Implement this method + + return false; + } + + /* + Problem 8 + Return the number that appears most frequently in the list. + + Example + Input: [1,3,2,3,4,3] + Output: 3 + */ + public static Integer mostFrequent(List numbers) { + + // TODO: Implement this method + + return null; + } + + /* + Problem 9 + Group words based on their length. + + Example + Input: ["cat","dog","elephant","ant"] + + Output: + { + 3 = ["cat","dog","ant"], + 8 = ["elephant"] + } + */ + public static Map> groupByLength(List words) { + + // TODO: Implement this method + + return null; + } + + /* + Problem 10 + Return the maximum sum of any window of size k. + + Example + numbers = [2,1,5,1,3,2] + k = 3 + + Output: 9 + */ + public static int maxSlidingWindowSum(List numbers, int k) { + + // TODO: Implement this method + + return 0; + } + } +} diff --git a/src/main/java/Hierachy/01-README.md b/src/main/java/Hierachy/01-README.md new file mode 100644 index 0000000..d84a981 --- /dev/null +++ b/src/main/java/Hierachy/01-README.md @@ -0,0 +1,194 @@ +```markdown +# Java Collections Hierarchy Overview + +Before learning individual collections, it is important to understand how the **Java Collections Framework is organized**. + +This section introduces the **structure of the framework** and how the major interfaces and classes relate to each other. + +Understanding the hierarchy helps developers: +- Choose the correct data structure +- Write flexible code using interfaces +- Understand why certain methods exist in some structures but not others + +--- + +# The Java Collections Hierarchy + +The Collections Framework is organized around **interfaces and implementations**. + +Interfaces define behavior. +Classes implement those behaviors. + +``` + +Iterable +↓ +Collection +↓ +List Set Queue +↓ ↓ ↓ +ArrayList HashSet PriorityQueue +LinkedList LinkedHashSet +Vector TreeSet +Stack + +``` + +Important note: + +``` + +Map +↓ +HashMap +LinkedHashMap +TreeMap + +``` + +`Map` is part of the Java Collections Framework but **does not extend Collection**. + +--- + +# Key Interfaces + +## Iterable + +Root interface for anything that can be looped over. + +Provides: + +``` + +Iterator iterator(); + +``` + +Allows enhanced for-loops. + +--- + +## Collection + +Represents a **group of objects**. + +Common methods: + +``` + +add() +remove() +contains() +size() +clear() + +```` + +Extended by: +- List +- Set +- Queue + +--- + +## List + +An **ordered collection**. + +Characteristics: +- Allows duplicates +- Maintains insertion order +- Supports indexing + +Examples: + +- ArrayList +- LinkedList +- Vector +- Stack + +--- + +## Set + +A collection that **does not allow duplicates**. + +Examples: + +- HashSet +- LinkedHashSet +- TreeSet + +--- + +## Queue + +A collection designed for **processing elements in order**. + +Common behavior: +- FIFO (First In First Out) + +Examples: + +- PriorityQueue +- ArrayDeque +- LinkedList + +--- + +## Map + +Stores **key-value pairs**. + +Key characteristics: + +- Keys must be unique +- Values can duplicate + +Examples: + +- HashMap +- LinkedHashMap +- TreeMap + +--- + +# Why Interfaces Matter + +Instead of writing: + +```java +ArrayList list = new ArrayList<>(); +```` + +Prefer: + +```java +List list = new ArrayList<>(); +``` + +Benefits: + +* More flexible code +* Easy to swap implementations +* Better design practices + +--- + +# Summary + +The Java Collections Framework is built on **interfaces and implementations**. + +Key concepts: + +* Iterable enables looping +* Collection defines core behaviors +* List provides ordered collections +* Set prevents duplicates +* Queue processes elements in order +* Map stores key-value relationships + +Understanding this hierarchy makes it easier to choose the right data structure. + +``` +``` diff --git a/src/main/java/Hierachy/02-NOTES.md b/src/main/java/Hierachy/02-NOTES.md new file mode 100644 index 0000000..9066968 --- /dev/null +++ b/src/main/java/Hierachy/02-NOTES.md @@ -0,0 +1,195 @@ +````markdown +# Java Collections Hierarchy Notes + +## Purpose of the Collections Framework + +The **Java Collections Framework** provides a standardized architecture for storing and manipulating groups of objects. + +Benefits include: +- Reusable data structures +- Improved performance +- Consistent interfaces across structures +- Easier algorithm implementation + +--- + +## Key Design Idea + +The framework is built around **interfaces and implementations**. + +Interfaces define **what operations are possible**. +Classes define **how those operations are implemented**. + +Example: + +```java +List list = new ArrayList<>(); +```` + +* `List` → interface +* `ArrayList` → implementation + +This design allows developers to change implementations without changing much code. + +--- + +## Core Hierarchy + +``` +Iterable + ↓ +Collection + ↓ +List / Set / Queue +``` + +All collection types can be **iterated** because they ultimately implement `Iterable`. + +--- + +## Iterable + +The root interface that enables looping. + +Key method: + +```java +Iterator iterator(); +``` + +This allows structures to work with: + +```java +for (Type item : collection) +``` + +--- + +## Collection + +Represents a **group of objects**. + +Common methods available to all collections: + +```java +add() +remove() +contains() +size() +isEmpty() +clear() +``` + +The `Collection` interface is extended by: + +* `List` +* `Set` +* `Queue` + +--- + +## List + +An ordered collection. + +Characteristics: + +* Maintains insertion order +* Allows duplicate elements +* Supports index-based access + +Examples: + +* `ArrayList` +* `LinkedList` +* `Vector` +* `Stack` + +--- + +## Set + +A collection that **does not allow duplicates**. + +Characteristics: + +* Each element must be unique +* Ordering depends on the implementation + +Examples: + +* `HashSet` → no guaranteed order +* `LinkedHashSet` → maintains insertion order +* `TreeSet` → sorted order + +--- + +## Queue + +A collection used to process elements in order. + +Typical behavior: + +**FIFO (First In, First Out)** + +Examples: + +* `PriorityQueue` +* `ArrayDeque` +* `LinkedList` + +--- + +## Map (Special Case) + +`Map` is part of the Collections Framework but **does not extend Collection**. + +It stores **key-value pairs** instead of individual elements. + +Rules: + +* Keys must be unique +* Values may be duplicated + +Examples: + +* `HashMap` +* `LinkedHashMap` +* `TreeMap` + +--- + +## Why Use Interfaces Instead of Classes + +Prefer this: + +```java +List numbers = new ArrayList<>(); +``` + +Instead of: + +```java +ArrayList numbers = new ArrayList<>(); +``` + +Benefits: + +* Flexibility +* Easier code maintenance +* Better software design + +--- + +## Big Picture + +The Java Collections Framework helps developers efficiently store and manage data. + +Understanding the hierarchy makes it easier to: + +* Choose the correct structure +* Write flexible code +* Understand algorithm behavior + +``` +``` diff --git a/src/main/java/Hierachy/Hierarchy.java b/src/main/java/Hierachy/Hierarchy.java new file mode 100644 index 0000000..b79931f --- /dev/null +++ b/src/main/java/Hierachy/Hierarchy.java @@ -0,0 +1,60 @@ +package Hierachy; + +import java.util.*; + +public class Hierarchy { + public static void main(String[] args) { + + // LIST EXAMPLE + List list = new ArrayList<>(); + list.add("Apple"); + list.add("Banana"); + list.add("Cherry"); + + System.out.println("List Example:"); + for (String item : list) { + System.out.println(item); + } + + System.out.println(); + + // SET EXAMPLE + Set set = new HashSet<>(); + set.add(10); + set.add(20); + set.add(20); // duplicate ignored + set.add(30); + + System.out.println("Set Example:"); + for (Integer num : set) { + System.out.println(num); + } + + System.out.println(); + + // QUEUE EXAMPLE + Queue queue = new LinkedList<>(); + queue.offer("Task1"); + queue.offer("Task2"); + queue.offer("Task3"); + + System.out.println("Queue Example:"); + while (!queue.isEmpty()) { + System.out.println(queue.poll()); + } + + System.out.println(); + + // MAP EXAMPLE + Map map = new HashMap<>(); + map.put("Alice", 90); + map.put("Bob", 85); + map.put("Charlie", 95); + + System.out.println("Map Example:"); + + for (Map.Entry entry : map.entrySet()) { + System.out.println(entry.getKey() + " -> " + entry.getValue()); + } + } +} diff --git a/src/main/java/Hierachy/PRACTICE.md b/src/main/java/Hierachy/PRACTICE.md new file mode 100644 index 0000000..2b885d9 --- /dev/null +++ b/src/main/java/Hierachy/PRACTICE.md @@ -0,0 +1,155 @@ +````markdown +# Practice Exercises: Java Collections Hierarchy + +These exercises help reinforce understanding of the **Java Collections Framework hierarchy** and the relationships between its core interfaces and implementations. + +--- + +# Multiple Choice + +## Question 1 + +Which interface allows an object to be used in an enhanced for-loop? + +A. Collection +B. Iterable +C. List +D. Queue + +--- + +## Question 2 + +Which interface is the parent of `List`, `Set`, and `Queue`? + +A. Iterable +B. Collection +C. Map +D. Deque + +--- + +## Question 3 + +Which of the following is **NOT part of the Collection hierarchy**? + +A. List +B. Set +C. Queue +D. Map + +--- + +## Question 4 + +Which collection type allows **duplicate elements and maintains order**? + +A. Set +B. List +C. Queue +D. TreeSet + +--- + +## Question 5 + +Which structure stores **key-value pairs**? + +A. List +B. Set +C. Queue +D. Map + +--- + +# True or False + +Write **True** or **False**. + +1. `ArrayList` implements the `List` interface. +2. `Set` allows duplicate elements. +3. `Map` stores elements using keys and values. +4. `Queue` typically follows FIFO behavior. +5. `Iterable` allows collections to be used in enhanced for-loops. + +--- + +# Short Answer + +## Question 1 + +What is the difference between an **interface** and a **class** in the Java Collections Framework? + +--- + +## Question 2 + +Why is it recommended to declare variables using interfaces like `List` instead of concrete classes like `ArrayList`? + +Example: + +```java +List list = new ArrayList<>(); +```` + +--- + +## Question 3 + +Name three interfaces that extend `Collection`. + +--- + +# Code Reading Exercise + +Look at the code below. + +```java +List fruits = new ArrayList<>(); +fruits.add("Apple"); +fruits.add("Banana"); +fruits.add("Cherry"); + +for (String fruit : fruits) { + System.out.println(fruit); +} +``` + +Questions: + +1. Which interface type is used for the variable? +2. Which class is used as the implementation? +3. Why can the enhanced for-loop be used here? + +--- + +# Coding Exercise + +Create a small program that demonstrates the following: + +1. A **List** that stores three names. +2. A **Set** that stores unique numbers. +3. A **Queue** that stores three tasks. +4. A **Map** that stores student names and grades. + +Print the contents of each structure. + +--- + +# Challenge Exercise + +Write a program that: + +1. Creates a **List of student names** +2. Creates a **Set of unique course names** +3. Creates a **Queue of tasks** +4. Creates a **Map that stores student → grade** + +Then: + +* Print each structure +* Add one new element to each structure +* Print them again + +``` +``` diff --git a/src/main/java/Iterable/Challenges/CustomIterableMini.java b/src/main/java/Iterable/Challenges/CustomIterableMini.java new file mode 100644 index 0000000..ce2516a --- /dev/null +++ b/src/main/java/Iterable/Challenges/CustomIterableMini.java @@ -0,0 +1,4 @@ +package Iterable.Challenges; + +public class CustomIterableMini { +} diff --git a/src/main/java/Iterable/Examples/ForEachLoopDemo.java b/src/main/java/Iterable/Examples/ForEachLoopDemo.java new file mode 100644 index 0000000..a6d2198 --- /dev/null +++ b/src/main/java/Iterable/Examples/ForEachLoopDemo.java @@ -0,0 +1,37 @@ +package Iterable.Examples; + +import java.util.ArrayList; +import java.util.List; + +public class ForEachLoopDemo { + public static void main(String[] args) { + + List students = new ArrayList<>(); + + students.add("Alex"); + students.add("Jordan"); + students.add("Taylor"); + students.add("Morgan"); + + System.out.println("Printing students using a for-each loop:"); + + // TODO: + // Use a for-each loop to print each student name + + + System.out.println("\nPrinting students in uppercase:"); + + // TODO: + // Use a for-each loop to print each name in uppercase + + + System.out.println("\nCount the number of students:"); + + int count = 0; + + // TODO: + // Use a for-each loop to count how many students are in the list + + System.out.println("Total students: " + count); + } +} diff --git a/src/main/java/Iterable/Examples/IteratorDemo.java b/src/main/java/Iterable/Examples/IteratorDemo.java new file mode 100644 index 0000000..b09fca7 --- /dev/null +++ b/src/main/java/Iterable/Examples/IteratorDemo.java @@ -0,0 +1,43 @@ +package Iterable.Examples; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +public class IteratorDemo { + public static void main(String[] args) { + + List numbers = new ArrayList<>(); + + numbers.add(10); + numbers.add(15); + numbers.add(20); + numbers.add(25); + numbers.add(30); + + System.out.println("Original list:"); + System.out.println(numbers); + + // Create iterator + Iterator iterator = numbers.iterator(); + + System.out.println("\nIterating using Iterator:"); + + // TODO: + // Use iterator.hasNext() and iterator.next() + // Print each number + + + System.out.println("\nRemoving odd numbers using Iterator"); + + iterator = numbers.iterator(); + + // TODO: + // Use iterator to remove odd numbers + // Remember: use iterator.remove() + + + System.out.println("\nUpdated list:"); + System.out.println(numbers); + } +} diff --git a/src/main/java/Iterable/Practice/IterableWarmups.java b/src/main/java/Iterable/Practice/IterableWarmups.java new file mode 100644 index 0000000..9e9de94 --- /dev/null +++ b/src/main/java/Iterable/Practice/IterableWarmups.java @@ -0,0 +1,84 @@ +package Iterable.Practice; + +import java.util.ArrayList; +import java.util.List; + +public class IterableWarmups { + public static void main(String[] args) { + + List numbers = new ArrayList<>(); + + numbers.add(3); + numbers.add(7); + numbers.add(10); + numbers.add(4); + numbers.add(8); + + System.out.println("Sum: " + sum(numbers)); + System.out.println("Even count: " + countEven(numbers)); + System.out.println("Max value: " + findMax(numbers)); + } + + + /* + PROBLEM 1 + Return the sum of all numbers in the iterable + */ + public static int sum(Iterable numbers) { + + int total = 0; + + // TODO: + // Use a for-each loop to calculate the sum + + return total; + } + + + /* + PROBLEM 2 + Count how many numbers are even + */ + public static int countEven(Iterable numbers) { + + int count = 0; + + // TODO: + // Loop through numbers + // Increment count if number is even + + return count; + } + + + /* + PROBLEM 3 + Return the maximum value + */ + public static int findMax(Iterable numbers) { + + int max = Integer.MIN_VALUE; + + // TODO: + // Loop through numbers + // Update max if current number is larger + + return max; + } + + + /* + PROBLEM 4 (BONUS) + Count how many times a word appears + */ + public static int countMatches(Iterable words, String target) { + + int count = 0; + + // TODO: + // Loop through words + // Compare each word to target + + return count; + } +} diff --git a/src/main/java/Iterable/README.md b/src/main/java/Iterable/README.md new file mode 100644 index 0000000..858f7e3 --- /dev/null +++ b/src/main/java/Iterable/README.md @@ -0,0 +1,178 @@ +````markdown +# Iterable (Condensed Guide) + +## What Is Iterable? + +`Iterable` is the **root interface** of the Java Collections Framework. + +It represents anything that can be **looped over**. + +If a class implements `Iterable`, it can be used in an enhanced for-loop: + +```java +for (Type item : collection) { + // use item +} +```` + +--- + +## Where It Fits + +``` +Iterable + ↓ +Collection + ↓ +List / Set / Queue +``` + +Every `List`, `Set`, and `Queue` is an `Iterable`. + +--- + +## What Iterable Provides + +`Iterable` defines one core method: + +```java +Iterator iterator(); +``` + +This allows Java to retrieve elements one at a time. + +--- + +## How the Enhanced For-Loop Works + +This: + +```java +for (String name : names) { + System.out.println(name); +} +``` + +Is equivalent to: + +```java +Iterator it = names.iterator(); + +while (it.hasNext()) { + String name = it.next(); + System.out.println(name); +} +``` + +The enhanced for-loop uses an `Iterator` behind the scenes. + +--- + +## Iterator Core Methods + +```java +it.hasNext(); // checks if another element exists +it.next(); // moves to next element +it.remove(); // safely removes current element +``` + +--- + +## Time Complexity + +| Operation | Complexity | +| -------------- | ---------- | +| Full traversal | O(n) | + +Where `n` = number of elements. + +--- + +## ⚠ Common Mistakes + +### Removing elements inside enhanced for-loop + +```java +for (Integer n : list) { + if (n % 2 == 0) { + list.remove(n); // ❌ Causes ConcurrentModificationException + } +} +``` + +### Correct way using Iterator + +```java +Iterator it = list.iterator(); + +while (it.hasNext()) { + if (it.next() % 2 == 0) { + it.remove(); + } +} +``` + +--- + +## When Iterable Matters + +You care about `Iterable` when: + +* Writing custom collections +* Enabling enhanced for-loops +* Needing controlled element traversal + +--- + +## Example: Custom Iterable + +```java +import java.util.Iterator; +import java.util.Arrays; + +public class NumberBox implements Iterable { + + private Integer[] numbers = {1, 2, 3}; + + @Override + public Iterator iterator() { + return Arrays.asList(numbers).iterator(); + } +} +``` + +Now this works: + +```java +NumberBox box = new NumberBox(); + +for (int n : box) { + System.out.println(n); +} +``` + +--- + +## Practice Ideas + +* Write a method that accepts `Iterable` and returns the sum +* Remove all odd numbers using `Iterator` +* Count elements greater than a value +* Create a simple custom class that implements `Iterable` + +--- + +## Summary + +Iterable = **the foundation of looping in Java Collections**. + +If a class implements `Iterable`, it: + +* Can be used in enhanced for-loops +* Provides an `Iterator` +* Enables safe traversal of elements + +Understanding `Iterable` helps you understand how all collections are traversed. + +``` +``` diff --git a/src/main/java/Lists/ArrayLists/ArrayListDemo.java b/src/main/java/Lists/ArrayLists/ArrayListDemo.java new file mode 100644 index 0000000..a63259f --- /dev/null +++ b/src/main/java/Lists/ArrayLists/ArrayListDemo.java @@ -0,0 +1,47 @@ +package Lists.ArrayLists; + +import java.util.ArrayList; +import java.util.List; + +public class ArrayListDemo { + public static void main(String[] args) { + + // Creating an ArrayList + List students = new ArrayList<>(); + + // Adding elements + students.add("Jordan"); + students.add("Taylor"); + students.add("Morgan"); + students.add("Alex"); + + System.out.println("Students: " + students); + + // Access element + System.out.println("First student: " + students.get(0)); + + // Update element + students.set(2, "Chris"); + System.out.println("After update: " + students); + + // Remove element + students.remove("Alex"); + System.out.println("After removal: " + students); + + // Size of list + System.out.println("Total students: " + students.size()); + + // Loop through ArrayList + System.out.println("\nLooping through students:"); + + for (String student : students) { + System.out.println(student); + } + + // Check if element exists + if (students.contains("Jordan")) { + System.out.println("\nJordan is in the list."); + } + } + +} diff --git a/src/main/java/Lists/ArrayLists/ArrayListProblems.java b/src/main/java/Lists/ArrayLists/ArrayListProblems.java new file mode 100644 index 0000000..baf4dfa --- /dev/null +++ b/src/main/java/Lists/ArrayLists/ArrayListProblems.java @@ -0,0 +1,105 @@ +package Lists.ArrayLists; + + +import java.util.ArrayList; +import java.util.List; + +public class ArrayListProblems { + public static void main(String[] args) { + + List numbers = new ArrayList<>(); + + numbers.add(4); + numbers.add(7); + numbers.add(2); + numbers.add(7); + numbers.add(9); + numbers.add(4); + + System.out.println("Sum: " + sum(numbers)); + System.out.println("Even Count: " + countEvens(numbers)); + System.out.println("Contains Duplicate: " + hasDuplicate(numbers)); + System.out.println("Max Value: " + findMax(numbers)); + System.out.println("Reversed List: " + reverse(numbers)); + } + + /* + Problem 1 + Return the sum of all numbers in the list. + + Example + Input: [1,2,3] + Output: 6 + */ + public static int sum(List nums) { + + // TODO: Implement this method + + return 0; + } + + /* + Problem 2 + Count how many EVEN numbers exist in the list. + + Example + Input: [1,2,4,7] + Output: 2 + */ + public static int countEvens(List nums) { + + // TODO: Implement this method + + return 0; + } + + /* + Problem 3 + Determine if the list contains any duplicate values. + + Example + Input: [1,2,3,1] + Output: true + + Input: [1,2,3] + Output: false + */ + public static boolean hasDuplicate(List nums) { + + // TODO: Implement this method + + return false; + } + + /* + Problem 4 + Return the largest number in the list. + + Example + Input: [4,2,7] + Output: 7 + */ + public static int findMax(List nums) { + + // TODO: Implement this method + + return 0; + } + + /* + Problem 5 + Return a NEW list that contains the elements of the original list in reverse order. + + Example + Input: [1,2,3] + Output: [3,2,1] + + The original list should remain unchanged. + */ + public static List reverse(List nums) { + + // TODO: Implement this method + + return null; + } +} diff --git a/src/main/java/Lists/ArrayLists/README.md b/src/main/java/Lists/ArrayLists/README.md new file mode 100644 index 0000000..7102e57 --- /dev/null +++ b/src/main/java/Lists/ArrayLists/README.md @@ -0,0 +1,128 @@ +````markdown +# 📘 ArrayList + +## What Is ArrayList? + +`ArrayList` is a resizable array implementation of the `List` interface. + +It: +- Maintains insertion order +- Allows duplicates +- Supports index-based access +- Grows dynamically + +```java +import java.util.ArrayList; +import java.util.List; + +List names = new ArrayList<>(); +```` + +--- + +## Where It Fits + +``` +Iterable → Collection → List → ArrayList +``` + +--- + +## How It Works + +* Backed by a dynamic array +* Resizes automatically when capacity is exceeded +* Fast random access +* Slower for insertions/removals in the middle + +--- + +## Time Complexity + +| Operation | Complexity | +| --------------------- | -------------- | +| `get(index)` | O(1) | +| `set(index)` | O(1) | +| `add(element)` | O(1) amortized | +| `add(index, element)` | O(n) | +| `remove(index)` | O(n) | +| `contains()` | O(n) | + +--- + +## Core Methods + +```java +list.add("Apple"); // add to end +list.add(0, "Banana"); // insert at index + +list.get(0); // access +list.set(1, "Orange"); // update + +list.remove(0); // remove by index +list.remove("Apple"); // remove by value + +list.size(); +list.isEmpty(); +list.contains("Apple"); +``` + +--- + +## Looping + +```java +for (String item : list) { + System.out.println(item); +} +``` + +```java +for (int i = 0; i < list.size(); i++) { + System.out.println(list.get(i)); +} +``` + +--- + +## Common Mistakes + +* Using `<=` instead of `<` in loops +* Removing elements inside enhanced for-loop +* Confusing capacity with size + +--- + +## When To Use ArrayList + +Use it when: + +* You need fast index access +* You mostly add to the end +* You want predictable order + +Avoid it when: + +* You frequently insert/remove at the beginning or middle +* You need uniqueness (use `Set`) + +--- + +## Practice Ideas + +* Reverse a list +* Remove duplicates +* Rotate list by k +* Find second largest number +* Two-sum problem + +--- + +### Summary + +ArrayList = **ordered, resizable, fast reads, slower middle inserts/removals**. + +Mastering when to use it vs LinkedList is key. + +``` +``` diff --git a/src/main/java/Lists/LinkedLists/LinkedListDemo.java b/src/main/java/Lists/LinkedLists/LinkedListDemo.java new file mode 100644 index 0000000..f53bda6 --- /dev/null +++ b/src/main/java/Lists/LinkedLists/LinkedListDemo.java @@ -0,0 +1,44 @@ +package Lists.LinkedLists; + +import java.util.LinkedList; + +public class LinkedListDemo { + public static void main(String[] args) { + + LinkedList tasks = new LinkedList<>(); + + // Adding elements + tasks.add("Check emails"); + tasks.add("Review pull requests"); + tasks.add("Write documentation"); + + System.out.println("Tasks: " + tasks); + + // Add to beginning + tasks.addFirst("Morning standup"); + + // Add to end + tasks.addLast("End of day report"); + + System.out.println("Updated Tasks: " + tasks); + + // Access first and last elements + System.out.println("First Task: " + tasks.getFirst()); + System.out.println("Last Task: " + tasks.getLast()); + + // Remove first element + tasks.removeFirst(); + + // Remove last element + tasks.removeLast(); + + System.out.println("After removals: " + tasks); + + // Loop through LinkedList + System.out.println("\nIterating through tasks:"); + + for (String task : tasks) { + System.out.println(task); + } + } +} diff --git a/src/main/java/Lists/LinkedLists/LinkedListProblems.java b/src/main/java/Lists/LinkedLists/LinkedListProblems.java new file mode 100644 index 0000000..178a2ba --- /dev/null +++ b/src/main/java/Lists/LinkedLists/LinkedListProblems.java @@ -0,0 +1,115 @@ +package Lists.LinkedLists; + +import java.util.LinkedList; + +public class LinkedListProblems { + public static void main(String[] args) { + + LinkedList numbers = new LinkedList<>(); + + numbers.add(10); + numbers.add(20); + numbers.add(30); + numbers.add(40); + numbers.add(50); + + addToFront(numbers, 5); + addToEnd(numbers, 60); + + System.out.println("List after additions: " + numbers); + + removeFirstElement(numbers); + removeLastElement(numbers); + + System.out.println("List after removals: " + numbers); + + System.out.println("First Element: " + getFirstElement(numbers)); + System.out.println("Last Element: " + getLastElement(numbers)); + } + + /* + Problem 1 + Add a value to the FRONT of the LinkedList. + + Example + Input: [10,20,30], value=5 + Output: [5,10,20,30] + */ + public static void addToFront(LinkedList list, int value) { + + // TODO: Implement this method + + } + + /* + Problem 2 + Add a value to the END of the LinkedList. + + Example + Input: [10,20,30], value=40 + Output: [10,20,30,40] + */ + public static void addToEnd(LinkedList list, int value) { + + // TODO: Implement this method + + } + + /* + Problem 3 + Remove the FIRST element from the LinkedList. + + Example + Input: [10,20,30] + Output: [20,30] + */ + public static void removeFirstElement(LinkedList list) { + + // TODO: Implement this method + + } + + /* + Problem 4 + Remove the LAST element from the LinkedList. + + Example + Input: [10,20,30] + Output: [10,20] + */ + public static void removeLastElement(LinkedList list) { + + // TODO: Implement this method + + } + + /* + Problem 5 + Return the FIRST element in the LinkedList. + + Example + Input: [10,20,30] + Output: 10 + */ + public static int getFirstElement(LinkedList list) { + + // TODO: Implement this method + + return 0; + } + + /* + Problem 6 + Return the LAST element in the LinkedList. + + Example + Input: [10,20,30] + Output: 30 + */ + public static int getLastElement(LinkedList list) { + + // TODO: Implement this method + + return 0; + } +} diff --git a/src/main/java/Lists/LinkedLists/README.md b/src/main/java/Lists/LinkedLists/README.md new file mode 100644 index 0000000..bca958d --- /dev/null +++ b/src/main/java/Lists/LinkedLists/README.md @@ -0,0 +1,175 @@ +````markdown +# LinkedList + +## What Is LinkedList? + +`LinkedList` is a **doubly linked list implementation** of the `List` interface. + +It: +- Maintains insertion order +- Allows duplicates +- Does NOT provide fast index access +- Can also function as a Queue or Deque + +```java +import java.util.LinkedList; +import java.util.List; + +List names = new LinkedList<>(); +```` + +--- + +## Where It Fits + +``` +Iterable → Collection → List → LinkedList + ↘ + Deque → Queue +``` + +`LinkedList` implements both: + +* `List` +* `Deque` (which extends `Queue`) + +--- + +## How It Works + +* Built from **nodes** +* Each node stores: + + * Data + * Reference to next node + * Reference to previous node +* No shifting of elements required + +Because it uses nodes: + +* Fast insertions/removals at beginning or middle +* Slow random index access + +--- + +## Time Complexity + +| Operation | Complexity | +| -------------------------------- | ---------- | +| `get(index)` | O(n) | +| `set(index)` | O(n) | +| `add(element)` | O(1) (end) | +| `addFirst()` / `addLast()` | O(1) | +| `add(index, element)` | O(n) | +| `removeFirst()` / `removeLast()` | O(1) | +| `contains()` | O(n) | + +--- + +## Core Methods (List Behavior) + +```java +list.add("Apple"); // add to end +list.add(0, "Banana"); // insert at index + +list.get(0); // access (slow) +list.set(1, "Orange"); // update + +list.remove(0); // remove by index +list.remove("Apple"); // remove by value +``` + +--- + +## Core Methods (Deque / Queue Behavior) + +```java +LinkedList queue = new LinkedList<>(); + +queue.addFirst("A"); +queue.addLast("B"); + +queue.removeFirst(); +queue.removeLast(); + +queue.peekFirst(); +queue.peekLast(); +``` + +--- + +## Looping + +Enhanced for-loop: + +```java +for (String item : list) { + System.out.println(item); +} +``` + +Traditional loop (slower due to indexing): + +```java +for (int i = 0; i < list.size(); i++) { + System.out.println(list.get(i)); // O(n) each time +} +``` + +⚠ Using index-based loops repeatedly makes it O(n²). + +--- + +## Common Mistakes + +* Using `get(i)` in large loops (slow) +* Assuming it has fast random access +* Forgetting it can act as a Queue or Deque + +--- + +## ArrayList vs LinkedList + +| Feature | ArrayList | LinkedList | +| ------------- | ------------- | ------------------------ | +| Random Access | O(1) | O(n) | +| Insert Middle | O(n) | Faster | +| Remove Middle | O(n) | Faster | +| Memory Usage | Lower | Higher | +| Best For | Reading often | Frequent inserts/removes | + +--- + +## When To Use LinkedList + +Use it when: + +* You frequently insert/remove at the beginning +* You need Queue or Deque behavior +* You do not rely on heavy index access + +Avoid it when: + +* You frequently access by index +* You need fast random reads + +--- + +## Practice Ideas + +* Implement a queue using LinkedList +* Implement a stack using LinkedList +* Remove duplicates manually +* Insert element after every occurrence of X +* Simulate browser history navigation + +--- + +## Summary + +LinkedList = **node-based, flexible, fast inserts/removals, slow index access**. + +Use it when structure flexibility matters more than fast random reads. + +``` +``` diff --git a/src/main/java/Lists/Read.md b/src/main/java/Lists/Read.md new file mode 100644 index 0000000..966e642 --- /dev/null +++ b/src/main/java/Lists/Read.md @@ -0,0 +1,201 @@ +````markdown +# List (Condensed Guide) + +## What Is a List? + +A `List` is an **ordered collection** that allows **duplicate elements**. + +Key characteristics: +- Maintains **insertion order** +- Allows **duplicate values** +- Supports **index-based access** +- Elements can be added, removed, or updated by position + +Common implementations: +- `ArrayList` +- `LinkedList` +- `Vector` +- `Stack` + +```java +import java.util.List; +import java.util.ArrayList; + +List names = new ArrayList<>(); +```` + +--- + +## Where It Fits + +``` +Iterable + ↓ +Collection + ↓ +List +``` + +Implementations include: + +``` +List + ↓ +ArrayList +LinkedList +Vector +Stack +``` + +--- + +## How It Works + +A `List` stores elements **in a specific order**. + +Example: + +``` +add("Apple") +add("Banana") +add("Cherry") +``` + +Result: + +``` +[Apple, Banana, Cherry] +``` + +Each element has an **index position** starting from `0`. + +--- + +## Time Complexity (Typical) + +Depends on the implementation. + +### ArrayList + +| Operation | Complexity | +| --------------- | -------------- | +| `get(index)` | O(1) | +| `add(element)` | O(1) amortized | +| `remove(index)` | O(n) | + +### LinkedList + +| Operation | Complexity | +| --------------- | ---------- | +| `get(index)` | O(n) | +| `addFirst()` | O(1) | +| `removeFirst()` | O(1) | + +--- + +## Core Methods + +```java +list.add("Apple"); // add element +list.add(0, "Banana"); // insert at index + +list.get(0); // access element +list.set(0, "Orange"); // update element + +list.remove(0); // remove element + +list.size(); // number of elements +list.isEmpty(); // check if empty +``` + +--- + +## Looping Through a List + +Enhanced for-loop: + +```java +for (String item : list) { + System.out.println(item); +} +``` + +Index-based loop: + +```java +for (int i = 0; i < list.size(); i++) { + System.out.println(list.get(i)); +} +``` + +--- + +## List vs Set + +| Feature | List | Set | +| ------------ | --------------- | ------------------------- | +| Duplicates | Allowed | Not allowed | +| Ordering | Maintains order | Depends on implementation | +| Index access | Yes | No | + +--- + +## When To Use List + +Use a List when you need: + +* Ordered data +* Duplicate elements +* Index-based access +* Sequential processing + +Examples: + +* Storing names +* Managing playlists +* Processing ordered data +* Maintaining history logs + +--- + +## Example + +```java +List fruits = new ArrayList<>(); + +fruits.add("Apple"); +fruits.add("Banana"); +fruits.add("Cherry"); + +System.out.println(fruits.get(1)); +``` + +Output: + +``` +Banana +``` + +--- + +## Practice Ideas + +* Reverse a list +* Find the second largest number +* Remove duplicates from a list +* Merge two lists + +--- + +## Summary + +List is an **ordered collection that allows duplicates and supports index-based access**. + +Key characteristics: + +* Maintains insertion order +* Allows duplicate elements +* Provides indexing operations + +``` +``` diff --git a/src/main/java/Lists/Vector/README.md b/src/main/java/Lists/Vector/README.md new file mode 100644 index 0000000..4f140e4 --- /dev/null +++ b/src/main/java/Lists/Vector/README.md @@ -0,0 +1,148 @@ +````markdown +# Vector + +## What Is Vector? + +`Vector` is a **resizable array implementation** of the `List` interface. + +It: +- Maintains insertion order +- Allows duplicate elements +- Supports index-based access +- Is **synchronized (thread-safe)** + +⚠ `Vector` is considered a **legacy class**. Modern Java code usually uses `ArrayList` instead. + +```java +import java.util.Vector; +import java.util.List; + +List items = new Vector<>(); +```` + +--- + +## Where It Fits + +``` +Iterable + ↓ +Collection + ↓ +List + ↓ +Vector +``` + +⚠ `Stack` extends `Vector`. + +--- + +## How It Works + +* Backed by a **dynamic array** +* Automatically resizes when capacity is exceeded +* Methods are **synchronized**, meaning thread-safe +* Slightly slower than `ArrayList` due to synchronization overhead + +--- + +## ⏱ Time Complexity + +| Operation | Complexity | +| --------------------- | -------------- | +| `get(index)` | O(1) | +| `set(index)` | O(1) | +| `add(element)` | O(1) amortized | +| `add(index, element)` | O(n) | +| `remove(index)` | O(n) | +| `contains()` | O(n) | + +Performance is similar to `ArrayList`, but slower due to synchronization. + +--- + +## Core Methods + +```java +vector.add("Apple"); // add to end +vector.add(0, "Banana"); // insert at index + +vector.get(0); // access element +vector.set(1, "Orange"); // update element + +vector.remove(0); // remove by index +vector.remove("Apple"); // remove by value + +vector.size(); +vector.isEmpty(); +vector.contains("Apple"); +``` + +--- + +## What Does “Synchronized” Mean? + +All major methods are **thread-safe**. + +This means: + +* Multiple threads can safely modify the vector +* Internal locking prevents data corruption + +However, this makes operations slightly slower. + +--- + +## Common Mistakes + +* Using `Vector` in single-threaded applications (unnecessary overhead) +* Confusing `Vector` with `ArrayList` +* Forgetting it is a legacy class + +--- + +## Vector vs ArrayList + +| Feature | Vector | ArrayList | +| ------------ | ------ | --------- | +| Thread-safe | Yes | No | +| Performance | Slower | Faster | +| Modern usage | Rare | Preferred | +| Legacy | Yes | No | + +--- + +## When To Use Vector + +Use it when: + +* You need built-in thread safety +* Maintaining legacy systems + +Avoid it when: + +* Writing modern applications +* Thread safety is not required + +--- + +## Practice Ideas + +* Compare performance of `Vector` vs `ArrayList` +* Convert legacy `Vector` code to `ArrayList` +* Simulate multi-threaded access (advanced) + +--- + +## Summary + +Vector = **thread-safe dynamic array (legacy)**. + +Modern best practice: + +* Use `ArrayList` for most applications +* Use concurrency utilities instead of relying on `Vector`. + +``` +``` diff --git a/src/main/java/Maps/HashMap/HashMapDemo.java b/src/main/java/Maps/HashMap/HashMapDemo.java new file mode 100644 index 0000000..53df45b --- /dev/null +++ b/src/main/java/Maps/HashMap/HashMapDemo.java @@ -0,0 +1,53 @@ +package Maps.HashMap; + +import java.util.HashMap; +import java.util.Map; + +public class HashMapDemo { + public static void main(String[] args) { + + Map studentScores = new HashMap<>(); + + // Adding key-value pairs + studentScores.put("Jordan", 92); + studentScores.put("Taylor", 85); + studentScores.put("Morgan", 88); + + System.out.println("Student Scores: " + studentScores); + + // Access value by key + int score = studentScores.get("Jordan"); + System.out.println("Jordan's Score: " + score); + + // Check if key exists + if (studentScores.containsKey("Taylor")) { + System.out.println("Taylor is in the map."); + } + + // Update value + studentScores.put("Morgan", 90); + System.out.println("Updated Scores: " + studentScores); + + // Remove entry + studentScores.remove("Taylor"); + System.out.println("After Removal: " + studentScores); + + // Loop through keys + System.out.println("\nKeys:"); + for (String key : studentScores.keySet()) { + System.out.println(key); + } + + // Loop through values + System.out.println("\nValues:"); + for (Integer value : studentScores.values()) { + System.out.println(value); + } + + // Loop through entries + System.out.println("\nEntries:"); + for (Map.Entry entry : studentScores.entrySet()) { + System.out.println(entry.getKey() + " -> " + entry.getValue()); + } + } +} diff --git a/src/main/java/Maps/HashMap/HashMapProblems.java b/src/main/java/Maps/HashMap/HashMapProblems.java new file mode 100644 index 0000000..04b5567 --- /dev/null +++ b/src/main/java/Maps/HashMap/HashMapProblems.java @@ -0,0 +1,98 @@ +package Maps.HashMap; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class HashMapProblems { + public static void main(String[] args) { + + Map inventory = new HashMap<>(); + + addItem(inventory, "Apples", 10); + addItem(inventory, "Bananas", 5); + addItem(inventory, "Oranges", 8); + + System.out.println("Inventory: " + inventory); + + System.out.println("Quantity of Apples: " + getQuantity(inventory, "Apples")); + + updateQuantity(inventory, "Bananas", 12); + System.out.println("Updated Inventory: " + inventory); + + removeItem(inventory, "Oranges"); + System.out.println("After Removal: " + inventory); + } + + /* + Problem 1 + Add an item and its quantity to the map. + + Example + Input: ("Apples", 10) + Output: {"Apples"=10} + */ + public static void addItem(Map map, String item, int quantity) { + + // TODO: Implement this method + + } + + /* + Problem 2 + Return the quantity of a specific item. + + Example + Input: ("Apples") + Output: 10 + */ + public static int getQuantity(Map map, String item) { + + // TODO: Implement this method + + return 0; + } + + /* + Problem 3 + Update the quantity of an existing item. + + Example + Input: ("Bananas", 12) + Output: {"Bananas"=12} + */ + public static void updateQuantity(Map map, String item, int newQuantity) { + + // TODO: Implement this method + + } + + /* + Problem 4 + Remove an item from the map. + + Example + Input: ("Oranges") + Output: item removed + */ + public static void removeItem(Map map, String item) { + + // TODO: Implement this method + + } + + /* + Problem 5 + Count how many times each number appears in a list. + + Example + Input: [1,2,2,3,3,3] + Output: {1=1, 2=2, 3=3} + */ + public static Map countFrequency(List numbers) { + + // TODO: Implement this method + + return null; + } +} diff --git a/src/main/java/Maps/HashMap/README.md b/src/main/java/Maps/HashMap/README.md new file mode 100644 index 0000000..321d09b --- /dev/null +++ b/src/main/java/Maps/HashMap/README.md @@ -0,0 +1,206 @@ +````markdown +# HashMap (Condensed Guide) + +## What Is HashMap? + +`HashMap` is a **Map implementation** that stores **key-value pairs**. + +It: +- Uses **keys to quickly retrieve values** +- Does **not maintain ordering** +- Allows **one null key** +- Allows **multiple null values** + +```java +import java.util.HashMap; +import java.util.Map; + +Map scores = new HashMap<>(); +```` + +--- + +## Where It Fits + +``` +Map + ↓ +HashMap +``` + +⚠ `Map` is **not part of the Collection hierarchy**, but it is part of the Java Collections Framework. + +--- + +## How It Works + +`HashMap` stores data using **hashing**. + +Steps when storing data: + +1. The key’s `hashCode()` is calculated +2. The hash determines a **bucket location** +3. The value is stored at that location + +Because of hashing: + +* Lookups are extremely fast +* Keys must implement proper `equals()` and `hashCode()` + +--- + +## Time Complexity + +| Operation | Complexity | +| --------------- | ------------ | +| `put()` | O(1) average | +| `get()` | O(1) average | +| `remove()` | O(1) average | +| `containsKey()` | O(1) | + +Worst case (rare collisions) → O(n) + +--- + +## Core Methods + +### Add / Update + +```java +map.put("Alice", 90); +map.put("Bob", 85); +``` + +--- + +### Access Value + +```java +map.get("Alice"); +``` + +--- + +### Remove Entry + +```java +map.remove("Bob"); +``` + +--- + +### Check Key + +```java +map.containsKey("Alice"); +``` + +--- + +### Size + +```java +map.size(); +``` + +--- + +## Looping Through a HashMap + +### Using entrySet() + +```java +for (Map.Entry entry : map.entrySet()) { + System.out.println(entry.getKey() + " -> " + entry.getValue()); +} +``` + +--- + +### Using keySet() + +```java +for (String key : map.keySet()) { + System.out.println(key + " -> " + map.get(key)); +} +``` + +--- + +## ⚠ Common Mistakes + +* Expecting HashMap to maintain order +* Using mutable objects as keys +* Forgetting `equals()` and `hashCode()` rules + +--- + +## HashMap vs TreeMap vs LinkedHashMap + +| Feature | HashMap | LinkedHashMap | TreeMap | +| -------- | --------------- | --------------- | ----------- | +| Order | None | Insertion order | Sorted | +| Speed | Fastest | Slightly slower | Slower | +| Use Case | General purpose | Maintain order | Sorted keys | + +--- + +## When To Use HashMap + +Use HashMap when you need: + +* Fast key lookups +* Data associations +* Frequency counting +* Caching or indexing + +Common examples: + +* Word frequency counters +* User ID → profile lookup +* Student name → grade mapping + +--- + +## Example + +```java +Map wordCount = new HashMap<>(); + +wordCount.put("java", 3); +wordCount.put("python", 2); + +System.out.println(wordCount.get("java")); +``` + +Output: + +``` +3 +``` + +--- + +## Practice Ideas + +* Count word frequencies in a sentence +* Implement a phone directory +* Find the first non-repeating character +* Solve the Two-Sum problem + +--- + +## Summary + +HashMap = **fast key-value storage using hashing**. + +Key characteristics: + +* O(1) lookups +* No ordering +* Unique keys + +Understanding HashMap is essential for solving many algorithm problems efficiently. + +``` +``` diff --git a/src/main/java/Maps/LinkedHashMap/LinkedHashMapDemo.java b/src/main/java/Maps/LinkedHashMap/LinkedHashMapDemo.java new file mode 100644 index 0000000..dead1c0 --- /dev/null +++ b/src/main/java/Maps/LinkedHashMap/LinkedHashMapDemo.java @@ -0,0 +1,37 @@ +package Maps.LinkedHashMap; + +import java.util.LinkedHashMap; +import java.util.Map; + +public class LinkedHashMapDemo { + public static void main(String[] args) { + + Map scores = new LinkedHashMap<>(); + + // Adding key-value pairs + scores.put("Jordan", 95); + scores.put("Taylor", 87); + scores.put("Morgan", 90); + scores.put("Alex", 82); + + System.out.println("Scores: " + scores); + + // Notice the insertion order is preserved + System.out.println("\nIterating through entries:"); + + for (Map.Entry entry : scores.entrySet()) { + System.out.println(entry.getKey() + " -> " + entry.getValue()); + } + + // Updating a value + scores.put("Taylor", 91); + System.out.println("\nAfter updating Taylor: " + scores); + + // Removing a key + scores.remove("Alex"); + System.out.println("\nAfter removing Alex: " + scores); + + // Accessing values + System.out.println("\nJordan's Score: " + scores.get("Jordan")); + } +} diff --git a/src/main/java/Maps/LinkedHashMap/LinkedHashMapProblems.java b/src/main/java/Maps/LinkedHashMap/LinkedHashMapProblems.java new file mode 100644 index 0000000..e8bbdc2 --- /dev/null +++ b/src/main/java/Maps/LinkedHashMap/LinkedHashMapProblems.java @@ -0,0 +1,97 @@ +package Maps.LinkedHashMap; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +public class LinkedHashMapProblems { + public static void main(String[] args) { + + Map studentGrades = new LinkedHashMap<>(); + + addStudent(studentGrades, "Jordan", 90); + addStudent(studentGrades, "Taylor", 85); + addStudent(studentGrades, "Morgan", 88); + + System.out.println("Students: " + studentGrades); + + updateGrade(studentGrades, "Taylor", 92); + System.out.println("Updated Grades: " + studentGrades); + + removeStudent(studentGrades, "Morgan"); + System.out.println("After Removal: " + studentGrades); + } + + /* + Problem 1 + Add a student and their grade to the LinkedHashMap. + + Example + Input: ("Jordan", 90) + Output: {"Jordan"=90} + */ + public static void addStudent(Map map, String name, int grade) { + + // TODO: Implement this method + + } + + /* + Problem 2 + Update the grade of an existing student. + + Example + Input: ("Taylor", 92) + Output: {"Taylor"=92} + */ + public static void updateGrade(Map map, String name, int newGrade) { + + // TODO: Implement this method + + } + + /* + Problem 3 + Remove a student from the LinkedHashMap. + + Example + Input: ("Morgan") + Output: Student removed from map + */ + public static void removeStudent(Map map, String name) { + + // TODO: Implement this method + + } + + /* + Problem 4 + Return the first student inserted into the LinkedHashMap. + + Example + Input: {"Jordan"=90, "Taylor"=85} + Output: "Jordan" + */ + public static String getFirstInserted(Map map) { + + // TODO: Implement this method + + return null; + } + + /* + Problem 5 + Given a list of words, return a LinkedHashMap that counts + how many times each word appears while preserving insertion order. + + Example + Input: ["apple","banana","apple","orange"] + Output: {apple=2, banana=1, orange=1} + */ + public static Map wordFrequency(List words) { + + // TODO: Implement this method + + return null; + } +} diff --git a/src/main/java/Maps/LinkedHashMap/README.md b/src/main/java/Maps/LinkedHashMap/README.md new file mode 100644 index 0000000..82818a8 --- /dev/null +++ b/src/main/java/Maps/LinkedHashMap/README.md @@ -0,0 +1,205 @@ +````markdown +# 📘 LinkedHashMap (Condensed Guide) + +## 🧠 What Is LinkedHashMap? + +`LinkedHashMap` is a **Map implementation that maintains insertion order**. + +It: +- Stores **key-value pairs** +- Maintains **the order elements were added** +- Allows **one null key** +- Allows **multiple null values** + +```java +import java.util.LinkedHashMap; +import java.util.Map; + +Map scores = new LinkedHashMap<>(); +```` + +--- + +## 📌 Where It Fits + +``` +Map + ↓ +HashMap + ↓ +LinkedHashMap +``` + +`LinkedHashMap` extends `HashMap` but adds **ordering behavior**. + +--- + +## ⚙️ How It Works + +`LinkedHashMap` uses: + +* A **hash table** (like HashMap) for fast lookup +* A **doubly linked list** to maintain insertion order + +Because of this: + +* Lookups remain fast +* Iteration follows insertion order + +--- + +## ⏱ Time Complexity + +| Operation | Complexity | +| --------------- | ------------ | +| `put()` | O(1) average | +| `get()` | O(1) average | +| `remove()` | O(1) average | +| `containsKey()` | O(1) | + +Performance is very similar to `HashMap`. + +--- + +## 🔑 Core Methods + +### Add / Update + +```java +map.put("Alice", 90); +map.put("Bob", 85); +``` + +--- + +### Access Value + +```java +map.get("Alice"); +``` + +--- + +### Remove Entry + +```java +map.remove("Bob"); +``` + +--- + +### Check Key + +```java +map.containsKey("Alice"); +``` + +--- + +### Size + +```java +map.size(); +``` + +--- + +## 🔁 Looping Through LinkedHashMap + +Because it maintains insertion order: + +```java +for (Map.Entry entry : map.entrySet()) { + System.out.println(entry.getKey() + " -> " + entry.getValue()); +} +``` + +Example output: + +``` +Alice -> 90 +Bob -> 85 +Charlie -> 92 +``` + +The order matches the order elements were added. + +--- + +## ⚠ Common Mistakes + +* Assuming LinkedHashMap sorts keys (it does NOT) +* Forgetting that ordering is **insertion order**, not sorted order +* Using it when ordering does not matter (HashMap may be faster) + +--- + +## 🆚 HashMap vs LinkedHashMap vs TreeMap + +| Feature | HashMap | LinkedHashMap | TreeMap | +| -------- | --------------- | --------------- | ----------- | +| Order | None | Insertion order | Sorted | +| Speed | Fastest | Slightly slower | Slower | +| Use Case | General purpose | Maintain order | Sorted keys | + +--- + +## 🧪 When To Use LinkedHashMap + +Use LinkedHashMap when: + +* Order of insertion matters +* You want predictable iteration order +* You need HashMap speed but with ordering + +Common examples: + +* Caches +* Logs +* Maintaining user action history + +--- + +## 💡 Example + +```java +Map scores = new LinkedHashMap<>(); + +scores.put("Alice", 90); +scores.put("Bob", 85); +scores.put("Charlie", 92); + +System.out.println(scores); +``` + +Output: + +``` +{Alice=90, Bob=85, Charlie=92} +``` + +--- + +## 🧪 Practice Ideas + +* Count word frequency while preserving order +* Build a simple cache +* Remove duplicates from a list while preserving order +* Track user activity history + +--- + +## 🏁 Summary + +LinkedHashMap = **HashMap with predictable iteration order**. + +Key characteristics: + +* Fast lookups +* Maintains insertion order +* Slightly more overhead than HashMap + +Use it when you want **HashMap performance with consistent ordering**. + +``` +``` diff --git a/src/main/java/Maps/MapBasics/README.md b/src/main/java/Maps/MapBasics/README.md new file mode 100644 index 0000000..e3b3241 --- /dev/null +++ b/src/main/java/Maps/MapBasics/README.md @@ -0,0 +1,196 @@ +````markdown +# Map Basics (Condensed Guide) + +## What Is a Map? + +A `Map` is a data structure that stores **key-value pairs**. + +Each **key** maps to exactly **one value**. + +Rules: +- Keys must be **unique** +- Values **can be duplicated** +- Each key points to one value + +Example: + +```java +Key → Value +"John" → 90 +"Alice" → 85 +"Bob" → 78 +```` + +--- + +## Where It Fits + +``` +Map + ↓ +HashMap +LinkedHashMap +TreeMap +``` + +⚠ `Map` is **not part of the Collection hierarchy**, but it is part of the Java Collections Framework. + +--- + +## Why Maps Are Useful + +Maps allow you to **look up data quickly using a key**. + +Examples: + +* Username → Password +* Student → Grade +* Word → Frequency +* Product ID → Product + +--- + +## Creating a Map + +```java +import java.util.Map; +import java.util.HashMap; + +Map scores = new HashMap<>(); +``` + +Best practice: **use the interface type (`Map`)**. + +--- + +## 🔑 Core Map Methods + +### Add or Update + +```java +map.put("Alice", 90); +map.put("Bob", 85); +``` + +If the key already exists, the value is replaced. + +--- + +### Access a Value + +```java +map.get("Alice"); +``` + +Returns the value associated with the key. + +--- + +### Remove an Entry + +```java +map.remove("Bob"); +``` + +--- + +### Check for a Key + +```java +map.containsKey("Alice"); +``` + +--- + +### Check for a Value + +```java +map.containsValue(90); +``` + +--- + +### Get Map Size + +```java +map.size(); +``` + +--- + +## Looping Through a Map + +### Using `entrySet()` (Most Common) + +```java +for (Map.Entry entry : map.entrySet()) { + System.out.println(entry.getKey() + " -> " + entry.getValue()); +} +``` + +--- + +### Using `keySet()` + +```java +for (String key : map.keySet()) { + System.out.println(key + " -> " + map.get(key)); +} +``` + +--- + +### Looping Values Only + +```java +for (Integer value : map.values()) { + System.out.println(value); +} +``` + +--- + +## Time Complexity (Typical) + +| Operation | Complexity | +| --------------- | ------------ | +| `put()` | O(1) average | +| `get()` | O(1) average | +| `remove()` | O(1) average | +| `containsKey()` | O(1) | + +Actual performance depends on the implementation (`HashMap`, `TreeMap`, etc.). + +--- + +## ⚠ Common Mistakes + +* Expecting duplicate keys +* Forgetting `get()` returns `null` if key not found +* Confusing `keySet()` with `entrySet()` + +--- + +## Practice Ideas + +* Count word frequencies in a sentence +* Store student names and grades +* Build a phone directory +* Find the most frequent number in a list + +--- + +## Summary + +Map = **a structure that stores key-value relationships**. + +Key characteristics: + +* Unique keys +* Fast lookups +* Multiple implementations (`HashMap`, `LinkedHashMap`, `TreeMap`) + +Understanding Maps is essential for solving many real-world programming problems. + +``` +``` diff --git a/src/main/java/Maps/README.md b/src/main/java/Maps/README.md new file mode 100644 index 0000000..d8e7adb --- /dev/null +++ b/src/main/java/Maps/README.md @@ -0,0 +1,238 @@ +````markdown +# TreeMap (Condensed Guide) + +## What Is TreeMap? + +`TreeMap` is a `Map` implementation that stores key-value pairs in **sorted order based on the keys**. + +It: +- Stores data as **key-value pairs** +- Automatically **sorts keys** +- Does **not allow null keys** +- Allows multiple null values + +```java +import java.util.Map; +import java.util.TreeMap; + +Map scores = new TreeMap<>(); +```` + +--- + +## Where It Fits + +``` +Map + ↓ +SortedMap + ↓ +NavigableMap + ↓ +TreeMap +``` + +TreeMap implements both `SortedMap` and `NavigableMap`. + +--- + +## How It Works + +`TreeMap` is implemented using a **Red-Black Tree**, a type of self-balancing binary search tree. + +This means: + +* Keys are always stored in **sorted order** +* Insertions maintain tree balance +* Lookups are efficient but slower than `HashMap` + +Sorting can occur: + +* Using **natural ordering** (e.g., alphabetical, numerical) +* Using a **custom comparator** + +--- + +## Time Complexity + +| Operation | Complexity | +| --------------- | ---------- | +| `put()` | O(log n) | +| `get()` | O(log n) | +| `remove()` | O(log n) | +| `containsKey()` | O(log n) | + +TreeMap is slower than `HashMap` because it maintains sorting. + +--- + +## Core Methods + +### Add / Update + +```java +map.put("Alice", 90); +map.put("Bob", 85); +map.put("Charlie", 92); +``` + +Keys will automatically appear in sorted order. + +--- + +### Access Value + +```java +map.get("Alice"); +``` + +--- + +### Remove Entry + +```java +map.remove("Bob"); +``` + +--- + +### Check Key + +```java +map.containsKey("Alice"); +``` + +--- + +### Size + +```java +map.size(); +``` + +--- + +## SortedMap Features + +### First and Last Keys + +```java +map.firstKey(); +map.lastKey(); +``` + +--- + +### Submap (Range of Keys) + +```java +map.subMap("A", "M"); +``` + +Returns keys between `"A"` and `"M"`. + +--- + +## NavigableMap Features + +### Closest Keys + +```java +map.higherKey("Bob"); // next higher key +map.lowerKey("Bob"); // next lower key +``` + +### Ceiling / Floor + +```java +map.ceilingKey("Bob"); // smallest key >= "Bob" +map.floorKey("Bob"); // largest key <= "Bob" +``` + +--- + +## Looping Through TreeMap + +```java +for (Map.Entry entry : map.entrySet()) { + System.out.println(entry.getKey() + " -> " + entry.getValue()); +} +``` + +Output will always be **sorted by key**. + +--- + +## HashMap vs LinkedHashMap vs TreeMap + +| Feature | HashMap | LinkedHashMap | TreeMap | +| ------------ | -------------- | --------------- | ----------- | +| Ordering | None | Insertion order | Sorted | +| Lookup Speed | O(1) | O(1) | O(log n) | +| Null Keys | 1 allowed | 1 allowed | Not allowed | +| Use Case | General lookup | Maintain order | Sorted keys | + +--- + +## When To Use TreeMap + +Use TreeMap when: + +* You need **sorted keys** +* You need **range queries** +* You need **ordered iteration** + +Examples: + +* Leaderboards +* Sorted indexes +* Time-based event storage +* Range searching + +--- + +## Example + +```java +Map students = new TreeMap<>(); + +students.put(3, "Alice"); +students.put(1, "Bob"); +students.put(2, "Charlie"); + +System.out.println(students); +``` + +Output: + +``` +{1=Bob, 2=Charlie, 3=Alice} +``` + +Keys are automatically sorted. + +--- + +## Practice Ideas + +* Store numbers and return them in sorted order +* Build a leaderboard sorted by score +* Find the closest value to a target number +* Return elements in a range using `subMap()` + +--- + +## Summary + +TreeMap is a **sorted map implementation backed by a balanced tree**. + +Key characteristics: + +* Keys automatically sorted +* O(log n) operations +* Supports range queries and navigation methods + +Use TreeMap when ordered keys or range operations are required. + +``` +``` diff --git a/src/main/java/Maps/TreeMap/README.md b/src/main/java/Maps/TreeMap/README.md new file mode 100644 index 0000000..e69de29 diff --git a/src/main/java/Maps/TreeMap/TreeMapDemo.java b/src/main/java/Maps/TreeMap/TreeMapDemo.java new file mode 100644 index 0000000..0a0fdd5 --- /dev/null +++ b/src/main/java/Maps/TreeMap/TreeMapDemo.java @@ -0,0 +1,37 @@ +package Maps.TreeMap; + +import java.util.Map; +import java.util.TreeMap; + +public class TreeMapDemo { + public static void main(String[] args) { + + Map leaderboard = new TreeMap<>(); + + // Adding elements + leaderboard.put(3, "Jordan"); + leaderboard.put(1, "Taylor"); + leaderboard.put(4, "Morgan"); + leaderboard.put(2, "Alex"); + + System.out.println("Leaderboard (Sorted by Key): " + leaderboard); + + // Access a value + System.out.println("Rank 1: " + leaderboard.get(1)); + + // First and last keys + System.out.println("First Key: " + ((TreeMap) leaderboard).firstKey()); + System.out.println("Last Key: " + ((TreeMap) leaderboard).lastKey()); + + // Iterating through entries + System.out.println("\nLeaderboard Rankings:"); + + for (Map.Entry entry : leaderboard.entrySet()) { + System.out.println("Rank " + entry.getKey() + ": " + entry.getValue()); + } + + // Removing an entry + leaderboard.remove(2); + System.out.println("\nAfter removing rank 2: " + leaderboard); + } +} diff --git a/src/main/java/Maps/TreeMap/TreeMapProblems.java b/src/main/java/Maps/TreeMap/TreeMapProblems.java new file mode 100644 index 0000000..b101d2e --- /dev/null +++ b/src/main/java/Maps/TreeMap/TreeMapProblems.java @@ -0,0 +1,95 @@ +package Maps.TreeMap; + +import java.util.TreeMap; + +public class TreeMapProblems { + public static void main(String[] args) { + + TreeMap rankings = new TreeMap<>(); + + addPlayer(rankings, 3, "Jordan"); + addPlayer(rankings, 1, "Taylor"); + addPlayer(rankings, 2, "Morgan"); + + System.out.println("Rankings: " + rankings); + + System.out.println("Top Player: " + getTopPlayer(rankings)); + System.out.println("Lowest Ranked Player: " + getLowestPlayer(rankings)); + + removePlayer(rankings, 2); + System.out.println("After removal: " + rankings); + } + + /* + Problem 1 + Add a player to the TreeMap with their rank. + + Example + Input: (1, "Jordan") + Output: {1="Jordan"} + */ + public static void addPlayer(TreeMap map, int rank, String name) { + + // TODO: Implement this method + + } + + /* + Problem 2 + Return the player with the highest ranking (smallest key). + + Example + Input: {1="Jordan", 2="Taylor"} + Output: "Jordan" + */ + public static String getTopPlayer(TreeMap map) { + + // TODO: Implement this method + + return null; + } + + /* + Problem 3 + Return the player with the lowest ranking (largest key). + + Example + Input: {1="Jordan", 2="Taylor"} + Output: "Taylor" + */ + public static String getLowestPlayer(TreeMap map) { + + // TODO: Implement this method + + return null; + } + + /* + Problem 4 + Remove a player based on their rank. + + Example + Input: remove rank 2 + Output: player removed + */ + public static void removePlayer(TreeMap map, int rank) { + + // TODO: Implement this method + + } + + /* + Problem 5 + Return the next higher rank after the given rank. + + Example + Input: rank=2, map={1="A",2="B",3="C"} + Output: 3 + */ + public static Integer getNextRank(TreeMap map, int rank) { + + // TODO: Implement this method + + return null; + } +} diff --git a/src/main/java/Queues/ArrayDeque/ArrayDequeDemo.java b/src/main/java/Queues/ArrayDeque/ArrayDequeDemo.java new file mode 100644 index 0000000..f498386 --- /dev/null +++ b/src/main/java/Queues/ArrayDeque/ArrayDequeDemo.java @@ -0,0 +1,44 @@ +package Queues.ArrayDeque; + +import java.util.ArrayDeque; + +public class ArrayDequeDemo { + public static void main(String[] args) { + + ArrayDeque tasks = new ArrayDeque<>(); + + // Using ArrayDeque as a Queue (FIFO) + tasks.add("Task 1"); + tasks.add("Task 2"); + tasks.add("Task 3"); + + System.out.println("Queue Behavior: " + tasks); + + System.out.println("Removing from queue: " + tasks.poll()); + System.out.println("Queue after poll: " + tasks); + + // Using ArrayDeque as a Stack (LIFO) + ArrayDeque stack = new ArrayDeque<>(); + + stack.push(10); + stack.push(20); + stack.push(30); + + System.out.println("\nStack Behavior: " + stack); + + System.out.println("Pop element: " + stack.pop()); + System.out.println("Stack after pop: " + stack); + + // Adding to front and back + ArrayDeque deque = new ArrayDeque<>(); + + deque.addFirst("Start"); + deque.addLast("Middle"); + deque.addLast("End"); + + System.out.println("\nDeque behavior: " + deque); + + System.out.println("First element: " + deque.getFirst()); + System.out.println("Last element: " + deque.getLast()); + } +} diff --git a/src/main/java/Queues/ArrayDeque/ArrayDequeProblems.java b/src/main/java/Queues/ArrayDeque/ArrayDequeProblems.java new file mode 100644 index 0000000..dac03cf --- /dev/null +++ b/src/main/java/Queues/ArrayDeque/ArrayDequeProblems.java @@ -0,0 +1,108 @@ +package Queues.ArrayDeque; + +import java.util.ArrayDeque; + +public class ArrayDequeProblems { + public static void main(String[] args) { + + ArrayDeque numbers = new ArrayDeque<>(); + + addToFront(numbers, 10); + addToFront(numbers, 5); + addToBack(numbers, 20); + + System.out.println("Deque: " + numbers); + + removeFront(numbers); + System.out.println("After removing front: " + numbers); + + removeBack(numbers); + System.out.println("After removing back: " + numbers); + } + + /* + Problem 1 + Add a number to the FRONT of the deque. + + Example + Input: value = 5 + Output: [5] + */ + public static void addToFront(ArrayDeque deque, int value) { + + // TODO: Implement this method + + } + + /* + Problem 2 + Add a number to the BACK of the deque. + + Example + Input: value = 10 + Output: [5,10] + */ + public static void addToBack(ArrayDeque deque, int value) { + + // TODO: Implement this method + + } + + /* + Problem 3 + Remove the element at the FRONT of the deque. + + Example + Input: [5,10,20] + Output: [10,20] + */ + public static void removeFront(ArrayDeque deque) { + + // TODO: Implement this method + + } + + /* + Problem 4 + Remove the element at the BACK of the deque. + + Example + Input: [5,10,20] + Output: [5,10] + */ + public static void removeBack(ArrayDeque deque) { + + // TODO: Implement this method + + } + + /* + Problem 5 + Return the FIRST element in the deque without removing it. + + Example + Input: [5,10,20] + Output: 5 + */ + public static Integer peekFront(ArrayDeque deque) { + + // TODO: Implement this method + + return null; + } + + /* + Problem 6 + Return the LAST element in the deque without removing it. + + Example + Input: [5,10,20] + Output: 20 + */ + public static Integer peekBack(ArrayDeque deque) { + + // TODO: Implement this method + + return null; + } +} diff --git a/src/main/java/Queues/ArrayDeque/README.md b/src/main/java/Queues/ArrayDeque/README.md new file mode 100644 index 0000000..cb5878c --- /dev/null +++ b/src/main/java/Queues/ArrayDeque/README.md @@ -0,0 +1,211 @@ +````markdown +# ArrayDeque (Condensed Guide) + +## What Is ArrayDeque? + +`ArrayDeque` is a **resizable array implementation of the `Deque` interface**. + +It can function as both: +- A **Queue (FIFO)** +- A **Stack (LIFO)** + +It is typically **faster than `Stack` and `LinkedList` for stack and queue operations**. + +```java +import java.util.ArrayDeque; +import java.util.Deque; + +Deque deque = new ArrayDeque<>(); +```` + +--- + +## Where It Fits + +``` +Iterable + ↓ +Collection + ↓ +Queue + ↓ +Deque + ↓ +ArrayDeque +``` + +`ArrayDeque` implements the `Deque` interface, which supports operations at both ends. + +--- + +## How It Works + +`ArrayDeque` uses a **dynamic circular array** internally. + +This allows: + +* Fast insertions/removals at both ends +* Efficient memory usage +* No shifting of elements like `ArrayList` + +Important rule: + +* `ArrayDeque` **does NOT allow null elements**. + +--- + +## Time Complexity + +| Operation | Complexity | +| --------------- | ---------- | +| `addFirst()` | O(1) | +| `addLast()` | O(1) | +| `removeFirst()` | O(1) | +| `removeLast()` | O(1) | +| `peekFirst()` | O(1) | +| `peekLast()` | O(1) | + +Most operations run in constant time. + +--- + +## Core Methods + +### Add Elements + +```java +deque.addFirst(10); +deque.addLast(20); +``` + +--- + +### Remove Elements + +```java +deque.removeFirst(); +deque.removeLast(); +``` + +--- + +### Peek Elements + +```java +deque.peekFirst(); +deque.peekLast(); +``` + +--- + +## Using ArrayDeque as a Queue (FIFO) + +```java +Deque queue = new ArrayDeque<>(); + +queue.offerLast(1); +queue.offerLast(2); +queue.offerLast(3); + +queue.pollFirst(); // 1 +``` + +First element inserted is first removed. + +--- + +## Using ArrayDeque as a Stack (LIFO) + +```java +Deque stack = new ArrayDeque<>(); + +stack.push(1); +stack.push(2); +stack.push(3); + +stack.pop(); // 3 +``` + +Last element inserted is first removed. + +--- + +## Common Mistakes + +* Trying to store `null` values (not allowed) +* Confusing `addFirst()` vs `addLast()` +* Using `Stack` when `ArrayDeque` is preferred + +--- + +## ArrayDeque vs LinkedList + +| Feature | ArrayDeque | LinkedList | +| ------------- | ------------- | ------------ | +| Memory usage | Lower | Higher | +| Performance | Faster | Slower | +| Null elements | Not allowed | Allowed | +| Use case | Stack / Queue | General list | + +--- + +## When To Use ArrayDeque + +Use ArrayDeque when you need: + +* A **fast stack implementation** +* A **fast queue implementation** +* Operations at **both ends of a structure** + +Examples: + +* Breadth-first search +* Undo/redo systems +* Task scheduling +* Parentheses checking + +--- + +## Example + +```java +Deque tasks = new ArrayDeque<>(); + +tasks.addLast("Task1"); +tasks.addLast("Task2"); +tasks.addLast("Task3"); + +System.out.println(tasks.removeFirst()); +``` + +Output: + +``` +Task1 +``` + +--- + +## Practice Ideas + +* Implement a stack using ArrayDeque +* Reverse a string using a stack +* Simulate a queue of tasks +* Check balanced parentheses + +--- + +## Summary + +ArrayDeque is a **high-performance implementation of a double-ended queue**. + +Key characteristics: + +* Fast operations at both ends +* Can be used as stack or queue +* Does not allow null values + +It is generally the **preferred structure for stack and queue behavior in modern Java**. + +``` +``` diff --git a/src/main/java/Queues/Deque/DequeDemo.java b/src/main/java/Queues/Deque/DequeDemo.java new file mode 100644 index 0000000..b05ca20 --- /dev/null +++ b/src/main/java/Queues/Deque/DequeDemo.java @@ -0,0 +1,39 @@ +package Queues.Deque; + +import java.util.ArrayDeque; +import java.util.Deque; + +public class DequeDemo { + public static void main(String[] args) { + + Deque deque = new ArrayDeque<>(); + + // Add elements to the front + deque.addFirst("B"); + deque.addFirst("A"); + + // Add elements to the back + deque.addLast("C"); + deque.addLast("D"); + + System.out.println("Deque: " + deque); + + // Peek elements + System.out.println("First Element: " + deque.peekFirst()); + System.out.println("Last Element: " + deque.peekLast()); + + // Remove elements + System.out.println("Removed First: " + deque.removeFirst()); + System.out.println("Removed Last: " + deque.removeLast()); + + System.out.println("Deque after removals: " + deque); + + // Iterating through deque + System.out.println("\nIterating through deque:"); + + for (String item : deque) { + System.out.println(item); + } + } +} + diff --git a/src/main/java/Queues/Deque/DequeProblems.java b/src/main/java/Queues/Deque/DequeProblems.java new file mode 100644 index 0000000..7ef0c06 --- /dev/null +++ b/src/main/java/Queues/Deque/DequeProblems.java @@ -0,0 +1,100 @@ +package Queues.Deque; + +import java.util.Deque; + +public class DequeProblems { + public static void main(String[] args) { + + // You can test your methods here + + } + + /* + Problem 1 + Add a value to the FRONT of the deque. + + Example + Input: value = 5 + Output: [5] + */ + public static void addFront(Deque deque, int value) { + + // TODO: Implement this method + + } + + /* + Problem 2 + Add a value to the BACK of the deque. + + Example + Input: value = 10 + Output: [5,10] + */ + public static void addBack(Deque deque, int value) { + + // TODO: Implement this method + + } + + /* + Problem 3 + Remove and return the FRONT element of the deque. + + Example + Input: [5,10,15] + Output: 5 + */ + public static Integer removeFront(Deque deque) { + + // TODO: Implement this method + + return null; + } + + /* + Problem 4 + Remove and return the BACK element of the deque. + + Example + Input: [5,10,15] + Output: 15 + */ + public static Integer removeBack(Deque deque) { + + // TODO: Implement this method + + return null; + } + + /* + Problem 5 + Return the FRONT element without removing it. + + Example + Input: [5,10,15] + Output: 5 + */ + public static Integer peekFront(Deque deque) { + + // TODO: Implement this method + + return null; + } + + /* + Problem 6 + Return the BACK element without removing it. + + Example + Input: [5,10,15] + Output: 15 + */ + public static Integer peekBack(Deque deque) { + + // TODO: Implement this method + + return null; + } + +} diff --git a/src/main/java/Queues/Deque/README.md b/src/main/java/Queues/Deque/README.md new file mode 100644 index 0000000..da17b50 --- /dev/null +++ b/src/main/java/Queues/Deque/README.md @@ -0,0 +1,218 @@ +````markdown +# Deque (Condensed Guide) + +## What Is Deque? + +`Deque` stands for **Double-Ended Queue**. + +It is an interface that allows elements to be **added or removed from both the front and the back** of a structure. + +Because of this, a `Deque` can function as: +- A **Queue (FIFO)** +- A **Stack (LIFO)** + +Common implementations: +- `ArrayDeque` +- `LinkedList` + +```java +import java.util.Deque; +import java.util.ArrayDeque; + +Deque deque = new ArrayDeque<>(); +```` + +--- + +## Where It Fits + +``` +Iterable + ↓ +Collection + ↓ +Queue + ↓ +Deque +``` + +Classes that implement `Deque` include: + +* `ArrayDeque` +* `LinkedList` + +--- + +## How It Works + +A `Deque` allows operations on **both ends of the structure**. + +Front (Head) ←→ Back (Tail) + +You can: + +* Insert at the front +* Insert at the back +* Remove from the front +* Remove from the back + +This flexibility allows it to behave as both a **stack and queue**. + +--- + +## Time Complexity + +Typical implementations like `ArrayDeque`: + +| Operation | Complexity | +| --------------- | ---------- | +| `addFirst()` | O(1) | +| `addLast()` | O(1) | +| `removeFirst()` | O(1) | +| `removeLast()` | O(1) | +| `peekFirst()` | O(1) | +| `peekLast()` | O(1) | + +Operations are generally constant time. + +--- + +## Core Methods + +### Add Elements + +```java +deque.addFirst(10); +deque.addLast(20); +``` + +--- + +### Remove Elements + +```java +deque.removeFirst(); +deque.removeLast(); +``` + +--- + +### Peek Elements + +```java +deque.peekFirst(); +deque.peekLast(); +``` + +--- + +## Using Deque as a Queue (FIFO) + +```java +Deque queue = new ArrayDeque<>(); + +queue.offerLast(1); +queue.offerLast(2); +queue.offerLast(3); + +queue.pollFirst(); // 1 +``` + +First element added is the first removed. + +--- + +## Using Deque as a Stack (LIFO) + +```java +Deque stack = new ArrayDeque<>(); + +stack.push(1); +stack.push(2); +stack.push(3); + +stack.pop(); // 3 +``` + +Last element added is the first removed. + +--- + +## Common Mistakes + +* Confusing `Deque` with `Queue` +* Using `Stack` instead of `Deque` +* Forgetting that both ends can be used + +--- + +## Deque vs Queue + +| Feature | Queue | Deque | +| ----------------- | ----- | ----- | +| Insert at front | No | Yes | +| Insert at back | Yes | Yes | +| Remove from front | Yes | Yes | +| Remove from back | No | Yes | + +Deque is more flexible than a standard Queue. + +--- + +## When To Use Deque + +Use Deque when you need: + +* Operations at both ends of a structure +* A fast stack implementation +* A fast queue implementation + +Common use cases: + +* Browser history navigation +* Undo/redo systems +* Sliding window algorithms +* Task scheduling + +--- + +## Example + +```java +Deque tasks = new ArrayDeque<>(); + +tasks.addFirst("Task1"); +tasks.addLast("Task2"); + +System.out.println(tasks.removeFirst()); +``` + +Output: + +``` +Task1 +``` + +--- + +## Practice Ideas + +* Implement a stack using Deque +* Implement a queue using Deque +* Reverse elements using Deque +* Build a browser history system + +--- + +## Summary + +Deque is a **double-ended queue that allows insertion and removal from both ends**. + +Key characteristics: + +* More flexible than a Queue +* Can act as both stack and queue +* Implemented by structures like `ArrayDeque` and `LinkedList` + +``` +``` diff --git a/src/main/java/Queues/PriorityQueue/README.md b/src/main/java/Queues/PriorityQueue/README.md new file mode 100644 index 0000000..685cb11 --- /dev/null +++ b/src/main/java/Queues/PriorityQueue/README.md @@ -0,0 +1,207 @@ +````markdown +# PriorityQueue (Condensed Guide) + +## What Is PriorityQueue? + +`PriorityQueue` is a `Queue` implementation where elements are processed based on **priority instead of insertion order**. + +Elements with **higher priority are removed first**. + +By default: +- The **smallest element has the highest priority** (min-heap behavior). + +```java +import java.util.PriorityQueue; +import java.util.Queue; + +Queue pq = new PriorityQueue<>(); +```` + +--- + +## Where It Fits + +``` +Iterable + ↓ +Collection + ↓ +Queue + ↓ +PriorityQueue +``` + +`PriorityQueue` implements the `Queue` interface. + +--- + +## How It Works + +`PriorityQueue` is implemented using a **binary heap**. + +This means: + +* The smallest element is always at the front +* Elements are automatically reordered when inserted +* The queue is **not sorted when iterating** + +Example: + +``` +add(5) +add(2) +add(8) + +poll() → 2 +poll() → 5 +poll() → 8 +``` + +--- + +## Time Complexity + +| Operation | Complexity | +| --------- | ---------- | +| `offer()` | O(log n) | +| `poll()` | O(log n) | +| `peek()` | O(1) | +| `add()` | O(log n) | + +The heap structure keeps operations efficient. + +--- + +## Core Methods + +### Add Element + +```java +pq.offer(10); +pq.offer(5); +pq.offer(20); +``` + +--- + +### View Highest Priority Element + +```java +pq.peek(); +``` + +Returns the smallest element. + +--- + +### Remove Highest Priority Element + +```java +pq.poll(); +``` + +Removes the element with the highest priority. + +--- + +### Check Size + +```java +pq.size(); +``` + +--- + +## Example + +```java +Queue pq = new PriorityQueue<>(); + +pq.offer(30); +pq.offer(10); +pq.offer(20); + +System.out.println(pq.poll()); +System.out.println(pq.poll()); +System.out.println(pq.poll()); +``` + +Output: + +``` +10 +20 +30 +``` + +Elements are removed in priority order. + +--- + +## Custom Priority (Comparator) + +You can define custom priority rules. + +Example: Max-heap + +```java +PriorityQueue pq = new PriorityQueue<>( + (a, b) -> b - a +); +``` + +Now the **largest element comes first**. + +--- + +## Common Mistakes + +* Assuming iteration returns sorted order +* Forgetting that the smallest element has highest priority by default +* Expecting FIFO behavior like a normal queue + +--- + +## PriorityQueue vs Queue + +| Feature | Queue | PriorityQueue | +| --------- | -------------- | ---------------- | +| Ordering | FIFO | Priority-based | +| Removal | First inserted | Highest priority | +| Structure | Linear | Heap | + +--- + +## When To Use PriorityQueue + +Use it when tasks must be processed by priority, such as: + +* Task scheduling +* Job processing systems +* Dijkstra’s algorithm +* A* search +* Finding top K elements + +--- + +## Practice Ideas + +* Find the K smallest numbers +* Implement a task scheduler +* Build a leaderboard system +* Merge multiple sorted lists + +--- + +## Summary + +PriorityQueue is a **heap-based queue that processes elements by priority instead of insertion order**. + +Key characteristics: + +* Highest priority element removed first +* Efficient O(log n) insert/remove +* Supports custom ordering using comparators + +``` +``` diff --git a/src/main/java/Queues/Queue/README.md b/src/main/java/Queues/Queue/README.md new file mode 100644 index 0000000..f9e463a --- /dev/null +++ b/src/main/java/Queues/Queue/README.md @@ -0,0 +1,193 @@ +````markdown +# Queue (Condensed Guide) + +## What Is a Queue? + +A `Queue` is a data structure that follows the **First-In, First-Out (FIFO)** principle. + +The first element added is the first one removed. + +Think of it like a line at a store: +- The first person in line gets served first. + +Common implementations: +- `LinkedList` +- `ArrayDeque` +- `PriorityQueue` (special ordering) + +```java +import java.util.Queue; +import java.util.LinkedList; + +Queue queue = new LinkedList<>(); +```` + +--- + +## Where It Fits + +``` +Iterable + ↓ +Collection + ↓ +Queue +``` + +Classes that commonly implement `Queue` include: + +* `LinkedList` +* `ArrayDeque` +* `PriorityQueue` + +--- + +## How It Works + +Queue operations occur at two ends: + +Front (Head) → Element removed +Back (Tail) → Element inserted + +Example: + +``` +add(1) +add(2) +add(3) + +remove() → 1 +remove() → 2 +remove() → 3 +``` + +--- + +## Time Complexity + +Typical implementations (`LinkedList`, `ArrayDeque`): + +| Operation | Complexity | +| --------- | ---------- | +| `offer()` | O(1) | +| `poll()` | O(1) | +| `peek()` | O(1) | + +Queue operations are usually constant time. + +--- + +## Core Methods + +### Add Element + +```java +queue.add("A"); // throws exception if it fails +queue.offer("B"); // returns false if it fails +``` + +--- + +### Remove Element + +```java +queue.remove(); // throws exception if empty +queue.poll(); // returns null if empty +``` + +--- + +### View Front Element + +```java +queue.element(); // throws exception if empty +queue.peek(); // returns null if empty +``` + +--- + +## Looping Through a Queue + +```java +for (String item : queue) { + System.out.println(item); +} +``` + +--- + +## Common Mistakes + +* Calling `remove()` on an empty queue +* Expecting LIFO behavior (that is Stack behavior) +* Confusing `PriorityQueue` with FIFO queues + +--- + +## Queue vs Stack + +| Feature | Queue | Stack | +| ------- | ----- | ----- | +| Order | FIFO | LIFO | +| Insert | Back | Top | +| Remove | Front | Top | + +Queue processes elements in the order they arrive. + +--- + +## When To Use Queue + +Use Queue when processing tasks in order, such as: + +* Task scheduling +* Printer job management +* Breadth-first search (BFS) +* Customer service systems +* Message processing systems + +--- + +## Example + +```java +Queue numbers = new LinkedList<>(); + +numbers.offer(10); +numbers.offer(20); +numbers.offer(30); + +System.out.println(numbers.poll()); +``` + +Output: + +``` +10 +``` + +The first element added is the first removed. + +--- + +## Practice Ideas + +* Simulate a printer queue +* Process customer service requests +* Implement a ticketing system +* Perform breadth-first search on a graph + +--- + +## Summary + +Queue is a **FIFO data structure used for ordered processing of elements**. + +Key characteristics: + +* Elements added at the back +* Elements removed from the front +* Common implementations include `LinkedList` and `ArrayDeque` + +``` +``` diff --git a/src/main/java/Queues/Read.md b/src/main/java/Queues/Read.md new file mode 100644 index 0000000..e69de29 diff --git a/src/main/java/Sets/HashSet/HashSetDemo.java b/src/main/java/Sets/HashSet/HashSetDemo.java new file mode 100644 index 0000000..034d7bf --- /dev/null +++ b/src/main/java/Sets/HashSet/HashSetDemo.java @@ -0,0 +1,39 @@ +package Sets.HashSet; + +import java.util.HashSet; +import java.util.Set; + +public class HashSetDemo { + public static void main(String[] args) { + + Set fruits = new HashSet<>(); + + // Adding elements + fruits.add("Apple"); + fruits.add("Banana"); + fruits.add("Orange"); + fruits.add("Apple"); // duplicate + + System.out.println("Fruits: " + fruits); + + // Checking if element exists + if (fruits.contains("Banana")) { + System.out.println("Banana exists in the set."); + } + + // Removing an element + fruits.remove("Orange"); + + System.out.println("After removal: " + fruits); + + // Size of the set + System.out.println("Total unique fruits: " + fruits.size()); + + // Iterating through the set + System.out.println("\nIterating through set:"); + + for (String fruit : fruits) { + System.out.println(fruit); + } + } +} diff --git a/src/main/java/Sets/HashSet/HashSetProblems.java b/src/main/java/Sets/HashSet/HashSetProblems.java new file mode 100644 index 0000000..a36c570 --- /dev/null +++ b/src/main/java/Sets/HashSet/HashSetProblems.java @@ -0,0 +1,85 @@ +package Sets.HashSet; + +import java.util.List; +import java.util.Set; + +public class HashSetProblems { + public static void main(String[] args) { + + // You can test your methods here + + } + + /* + Problem 1 + Add an element to the set. + + Example + Input: "apple" + Output: {"apple"} + */ + public static void addElement(Set set, String value) { + + // TODO: Implement this method + + } + + /* + Problem 2 + Check if the set contains a value. + + Example + Input: "banana" + Output: true or false + */ + public static boolean containsValue(Set set, String value) { + + // TODO: Implement this method + + return false; + } + + /* + Problem 3 + Remove a value from the set. + + Example + Input: "apple" + Output: value removed + */ + public static void removeValue(Set set, String value) { + + // TODO: Implement this method + + } + + /* + Problem 4 + Return the number of unique elements in the set. + + Example + Input: {"apple","banana","apple"} + Output: 2 + */ + public static int getUniqueCount(Set set) { + + // TODO: Implement this method + + return 0; + } + + /* + Problem 5 + Given a list of integers, return a HashSet containing only the unique values. + + Example + Input: [1,2,2,3,3,3] + Output: {1,2,3} + */ + public static Set getUniqueValues(List numbers) { + + // TODO: Implement this method + + return null; + } +} diff --git a/src/main/java/Sets/HashSet/README.md b/src/main/java/Sets/HashSet/README.md new file mode 100644 index 0000000..e2e1df7 --- /dev/null +++ b/src/main/java/Sets/HashSet/README.md @@ -0,0 +1,177 @@ +````markdown +# HashSet (Condensed Guide) + +## What Is HashSet? + +`HashSet` is a `Set` implementation that stores **unique elements using hashing**. + +Key characteristics: +- No duplicate elements +- No guaranteed ordering +- Allows **one null element** +- Fast lookup, insertion, and removal + +```java +import java.util.Set; +import java.util.HashSet; + +Set numbers = new HashSet<>(); +```` + +--- + +## Where It Fits + +``` +Iterable + ↓ +Collection + ↓ +Set + ↓ +HashSet +``` + +`HashSet` is one of the most commonly used implementations of the `Set` interface. + +--- + +## How It Works + +`HashSet` uses a **hash table** internally. + +Steps when adding an element: + +1. The element’s `hashCode()` is calculated +2. The hash determines a storage location +3. The element is placed into a bucket + +Because of hashing: + +* Searching is very fast +* Order of elements is **not predictable** + +Example: + +``` +add(10) +add(20) +add(10) +``` + +Result: + +``` +10, 20 +``` + +Duplicate values are ignored. + +--- + +## Time Complexity + +| Operation | Complexity | +| ------------ | ------------ | +| `add()` | O(1) average | +| `remove()` | O(1) average | +| `contains()` | O(1) average | + +Worst case (many collisions) → O(n) + +--- + +## Core Methods + +```java +set.add(10); // add element +set.remove(10); // remove element +set.contains(10); // check element +set.size(); // number of elements +set.isEmpty(); // check if empty +``` + +--- + +## Looping Through a HashSet + +```java +for (Integer num : set) { + System.out.println(num); +} +``` + +Because HashSet does not guarantee ordering, elements may appear in any order. + +--- + +## HashSet vs LinkedHashSet vs TreeSet + +| Feature | HashSet | LinkedHashSet | TreeSet | +| -------- | -------------- | ---------------------- | --------------------- | +| Order | None | Insertion order | Sorted | +| Speed | Fastest | Slightly slower | Slower | +| Use Case | Unique storage | Ordered unique storage | Sorted unique storage | + +--- + +## When To Use HashSet + +Use HashSet when you need: + +* Unique elements +* Fast membership checking +* Removing duplicates + +Examples: + +* Unique usernames +* Removing duplicates from a list +* Tracking visited nodes in algorithms +* Fast lookup tables + +--- + +## Example + +```java +Set fruits = new HashSet<>(); + +fruits.add("Apple"); +fruits.add("Banana"); +fruits.add("Apple"); + +System.out.println(fruits); +``` + +Output: + +``` +[Apple, Banana] +``` + +The duplicate `"Apple"` is not stored. + +--- + +## Practice Ideas + +* Remove duplicates from a list +* Count unique numbers in an array +* Track visited nodes in graph traversal +* Compare HashSet with TreeSet ordering + +--- + +## Summary + +HashSet is a **fast implementation of the Set interface that stores unique elements using hashing**. + +Key characteristics: + +* No duplicates +* No guaranteed ordering +* Very fast lookup and insertion + +``` +``` diff --git a/src/main/java/Sets/LinkedHashSet/README.md b/src/main/java/Sets/LinkedHashSet/README.md new file mode 100644 index 0000000..003f3b9 --- /dev/null +++ b/src/main/java/Sets/LinkedHashSet/README.md @@ -0,0 +1,172 @@ +````markdown +# LinkedHashSet (Condensed Guide) + +## What Is LinkedHashSet? + +`LinkedHashSet` is a `Set` implementation that **stores unique elements while maintaining insertion order**. + +Key characteristics: +- No duplicate elements +- Maintains **insertion order** +- Slightly slower than `HashSet` +- Allows **one null element** + +```java +import java.util.Set; +import java.util.LinkedHashSet; + +Set names = new LinkedHashSet<>(); +```` + +--- + +## Where It Fits + +``` +Iterable + ↓ +Collection + ↓ +Set + ↓ +HashSet + ↓ +LinkedHashSet +``` + +`LinkedHashSet` extends `HashSet` but adds **ordering behavior**. + +--- + +## How It Works + +`LinkedHashSet` uses: + +* A **hash table** (like `HashSet`) for fast lookups +* A **doubly linked list** to maintain insertion order + +This allows: + +* Fast operations +* Predictable iteration order + +Example: + +``` +add("A") +add("B") +add("C") +``` + +Iteration order: + +``` +A, B, C +``` + +--- + +## Time Complexity + +| Operation | Complexity | +| ------------ | ------------ | +| `add()` | O(1) average | +| `remove()` | O(1) average | +| `contains()` | O(1) average | + +Performance is similar to `HashSet`, with a small overhead for maintaining order. + +--- + +## Core Methods + +```java +set.add("Apple"); +set.remove("Apple"); +set.contains("Apple"); +set.size(); +set.isEmpty(); +``` + +--- + +## Looping Through a LinkedHashSet + +```java +for (String name : set) { + System.out.println(name); +} +``` + +Elements will appear **in the order they were inserted**. + +--- + +## HashSet vs LinkedHashSet vs TreeSet + +| Feature | HashSet | LinkedHashSet | TreeSet | +| ----------- | ---------------------- | --------------- | --------------- | +| Ordering | None | Insertion order | Sorted | +| Performance | Fastest | Slightly slower | Slower | +| Use Case | General unique storage | Maintain order | Sorted elements | + +--- + +## When To Use LinkedHashSet + +Use LinkedHashSet when you need: + +* Unique elements +* Predictable insertion order +* Fast lookup operations + +Examples: + +* Removing duplicates while preserving order +* Tracking unique user actions +* Maintaining ordered unique logs + +--- + +## Example + +```java +Set fruits = new LinkedHashSet<>(); + +fruits.add("Apple"); +fruits.add("Banana"); +fruits.add("Apple"); + +System.out.println(fruits); +``` + +Output: + +``` +[Apple, Banana] +``` + +The duplicate `"Apple"` is ignored, and the insertion order is preserved. + +--- + +## Practice Ideas + +* Remove duplicates from a list while preserving order +* Store unique usernames in insertion order +* Track unique visited pages + +--- + +## Summary + +LinkedHashSet is a **Set implementation that preserves insertion order while ensuring uniqueness**. + +Key characteristics: + +* No duplicates +* Maintains insertion order +* Fast lookup using hashing + +``` +``` diff --git a/src/main/java/Sets/README.md b/src/main/java/Sets/README.md new file mode 100644 index 0000000..cfac719 --- /dev/null +++ b/src/main/java/Sets/README.md @@ -0,0 +1,157 @@ +````markdown +# Set (Condensed Guide) + +## What Is a Set? + +A `Set` is a collection that **does not allow duplicate elements**. + +Key characteristics: +- Stores **unique elements only** +- Does **not support indexing** +- Ordering depends on the implementation + +Common implementations: +- `HashSet` +- `LinkedHashSet` +- `TreeSet` + +```java +import java.util.Set; +import java.util.HashSet; + +Set numbers = new HashSet<>(); +```` + +--- + +## Where It Fits + +``` +Iterable + ↓ +Collection + ↓ +Set +``` + +Implementations include: + +``` +Set + ↓ +HashSet +LinkedHashSet +TreeSet +``` + +--- + +## How It Works + +A `Set` ensures every element is **unique**. + +If you try to insert a duplicate element, it will **not be added**. + +Example: + +``` +add(10) +add(20) +add(20) +add(30) +``` + +Result: + +``` +10, 20, 30 +``` + +The duplicate `20` is ignored. + +--- + +## Time Complexity (Typical HashSet) + +| Operation | Complexity | +| ------------ | ------------ | +| `add()` | O(1) average | +| `remove()` | O(1) average | +| `contains()` | O(1) average | + +Actual performance depends on the implementation. + +--- + +## Core Methods + +```java +set.add(10); // add element +set.remove(10); // remove element +set.contains(10); // check element +set.size(); // number of elements +set.isEmpty(); // check if empty +``` + +--- + +## Looping Through a Set + +```java +for (Integer num : set) { + System.out.println(num); +} +``` + +Sets do not support `get(index)` because they are not indexed. + +--- + +## Set Implementations + +| Implementation | Behavior | +| --------------- | ---------------------------- | +| `HashSet` | No ordering | +| `LinkedHashSet` | Maintains insertion order | +| `TreeSet` | Automatically sorts elements | + +--- + +## Set vs List + +| Feature | List | Set | +| ------------ | --------------- | ------------------------- | +| Duplicates | Allowed | Not allowed | +| Ordering | Maintains order | Depends on implementation | +| Index access | Yes | No | + +--- + +## When To Use Set + +Use a Set when you need: + +* Unique values +* Fast membership checks +* Removing duplicates from data + +Examples: + +* Unique usernames +* Tracking visited items +* Removing duplicate values from lists + +--- + +## Summary + +Set is a **collection that stores unique elements**. + +Key characteristics: + +* No duplicate elements +* No indexing +* Different implementations provide different ordering behavior + +``` +``` diff --git a/src/main/java/Sets/TreeSet/README.md b/src/main/java/Sets/TreeSet/README.md new file mode 100644 index 0000000..c040dc9 --- /dev/null +++ b/src/main/java/Sets/TreeSet/README.md @@ -0,0 +1,219 @@ +````markdown +# TreeSet (Condensed Guide) + +## What Is TreeSet? + +`TreeSet` is a `Set` implementation that **stores unique elements in sorted order**. + +Key characteristics: +- No duplicate elements +- Elements are automatically **sorted** +- Does **not allow null elements** +- Uses a **balanced tree structure** internally + +```java +import java.util.Set; +import java.util.TreeSet; + +Set numbers = new TreeSet<>(); +```` + +--- + +## Where It Fits + +``` +Iterable + ↓ +Collection + ↓ +Set + ↓ +SortedSet + ↓ +NavigableSet + ↓ +TreeSet +``` + +TreeSet implements both `SortedSet` and `NavigableSet`. + +--- + +## How It Works + +`TreeSet` is implemented using a **Red-Black Tree**, a type of self-balancing binary search tree. + +This ensures: + +* Elements remain **sorted** +* Insertions and removals maintain tree balance +* Efficient searching + +Example: + +``` +add(30) +add(10) +add(20) +``` + +Result: + +``` +10, 20, 30 +``` + +Elements are automatically sorted. + +--- + +## Time Complexity + +| Operation | Complexity | +| ------------ | ---------- | +| `add()` | O(log n) | +| `remove()` | O(log n) | +| `contains()` | O(log n) | + +TreeSet is slower than HashSet because it maintains sorted order. + +--- + +## Core Methods + +```java +set.add(10); +set.add(20); +set.add(30); + +set.remove(20); +set.contains(10); +set.size(); +``` + +--- + +## SortedSet Features + +TreeSet allows operations related to ordering. + +### First and Last Elements + +```java +set.first(); +set.last(); +``` + +--- + +### Subsets + +```java +set.subSet(10, 50); +``` + +Returns elements within the specified range. + +--- + +## NavigableSet Features + +### Find Closest Elements + +```java +set.higher(20); // smallest element greater than 20 +set.lower(20); // largest element less than 20 +``` + +### Ceiling and Floor + +```java +set.ceiling(20); // smallest element ≥ 20 +set.floor(20); // largest element ≤ 20 +``` + +--- + +## Looping Through a TreeSet + +```java +for (Integer num : set) { + System.out.println(num); +} +``` + +Elements will always appear **in sorted order**. + +--- + +## TreeSet vs HashSet vs LinkedHashSet + +| Feature | HashSet | LinkedHashSet | TreeSet | +| --------- | ---------- | ----------------- | ------------- | +| Order | None | Insertion order | Sorted | +| Speed | Fastest | Slightly slower | Slower | +| Structure | Hash table | Hash table + list | Balanced tree | + +--- + +## When To Use TreeSet + +Use TreeSet when you need: + +* Automatically **sorted unique elements** +* **Range queries** +* **Closest value searches** + +Examples: + +* Leaderboards +* Sorted indexes +* Range filtering + +--- + +## Example + +```java +Set numbers = new TreeSet<>(); + +numbers.add(50); +numbers.add(10); +numbers.add(30); + +System.out.println(numbers); +``` + +Output: + +``` +[10, 30, 50] +``` + +The elements are stored in sorted order. + +--- + +## Practice Ideas + +* Store numbers and automatically sort them +* Find the smallest and largest elements +* Retrieve values within a range +* Track unique sorted scores + +--- + +## Summary + +TreeSet is a **sorted Set implementation backed by a balanced tree**. + +Key characteristics: + +* Unique elements only +* Automatically sorted +* O(log n) operations +* Supports range and navigation operations + +``` +```