Posts

Cycle Sort in Java — An In-Depth Guide

Image
When preparing for interviews at top companies like Amazon, Google, and Microsoft , you will often encounter problems that require efficient in-place sorting . One such elegant yet lesser-known algorithm is Cycle Sort . Unlike traditional sorting algorithms, Cycle Sort minimizes the number of writes, making it highly efficient when write operations are costly. 🔹 What is Cycle Sort? Cycle Sort is an in-place, comparison-based sorting algorithm. It works by placing each element directly in its correct position using the concept of cycles . Once an element is placed in the right spot, we continue the cycle until the entire array is sorted. Key Features: Minimizes the number of write operations (best choice when memory writes are expensive). Performs sorting in-place with constant space complexity (O(1)). Has a time complexity of O(n²), which makes it less practical for large datasets. 🔹 How Cycle Sort Works Let’s break the algorithm into simple steps: Sta...

ArrayList vs LinkedList in Java

Image
Java’s Collections Framework provides two commonly used List implementations: ArrayList and LinkedList . While both implement the List interface , they differ in their underlying data structures, performance, and use cases. Let’s break down their differences with examples and diagrams. 1. Underlying Structure ArrayList → Backed by a dynamic array. Elements are stored in contiguous memory . LinkedList → Implemented as a doubly-linked list. Each node stores data + pointers to the previous and next node. Diagram: ArrayList (Dynamic Array) [ 0 ] → [ 1 ] → [ 2 ] → [ 3 ] → [ 4 ] (index based access) LinkedList (Doubly Linked Nodes) NULL ← [0 | *] ↔ [1 | *] ↔ [2 | *] ↔ [3 | *] → NULL 2. Code Example ArrayList Example: import java.util.*; public class ArrayListExample { public static void main(String[] args) { List list = new ArrayList<>(); list.add("Java"); list.add("Python"); list.add("C+...

ConcurrentHashMap vs Synchronized HashMap in Java

Image
Introduction In multi-threaded Java applications, managing shared data safely and efficiently is crucial. Two common approaches are using Synchronized HashMap (via Collections.synchronizedMap(...) ) and ConcurrentHashMap . While both aim to provide thread-safety, their implementations and performance characteristics differ significantly. This post explores these differences in detail. What is a Synchronized HashMap? Created by wrapping a regular HashMap using: Map<K, V> syncMap = Collections.synchronizedMap(new HashMap<>()); Enforces synchronization at the object level , meaning only one thread can access the map at any time (read or write). Supports null keys and values since it relies on HashMap behavior. Iterators are fail-fast , throwing ConcurrentModificationException if the map is modified while iterating. Simpler implementation, suitable when concurrency is low or performance is not cri...

Internal Working of Map & HashMap in Java (Interview Ready)

Image
🔹 Introduction In the Java Collections Framework, both Map and HashMap are essential for working with key-value pairs. This blog dives into their internal mechanics, including how objects are stored and retrieved, how collisions are managed, and what improvements Java 8 brought to the table. 1. What is a Map? A Map<K, V> is a data structure that stores unique keys associated with corresponding values. Common implementations include: HashMap – unordered, allows one null key and multiple null values TreeMap – sorted by keys LinkedHashMap – maintains insertion order 2. How HashMap Works Internally ➡️ Nodes & Buckets Internally, a HashMap uses an array of Node objects , where each node represents a key-value pair plus a pointer for chaining in case of collisions. class Node<K,V> { int hash; K key; V value; Node<K,V> next; } ➡️ Hashing & Index Calculation ...

Understanding Multiple Threads in Java

Image
Introduction In Java programming, achieving parallel execution of tasks is made possible using multithreading. This blog explores how to create and run multiple threads concurrently, why using start() is critical, how scheduling works, and additional tips like using sleep() for clearer outputs. Demonstrating Multiple Threads Let's start with a simple example. We define two threads—one to say “Hi” and another to say “Hello”. class HiThread extends Thread {   public void run() {     for(int i = 0; i < 5; i++) {       System.out.println("Hi");       try { Thread.sleep(500); } catch(Exception e) {}     }   } } class HelloThread extends Thread {   public void run() {     for(int i = 0; i < 5; i++) {       System.out.println("Hello");       try { Thread.sleep...

Threads in Java

Image
Introduction In modern applications, responsiveness and efficiency are essential. Whether you’re building a desktop app, a game, or a backend server, you often need to perform multiple tasks simultaneously. This is where Threads in Java come into play. Threads allow you to run multiple tasks concurrently, making programs faster and more efficient. In this blog, we’ll explore: What threads are and why they are important How to create and manage threads in Java The thread lifecycle Common problems like race conditions How to ensure thread safety What is a Thread? A thread is the smallest unit of execution in a program. While a process represents an entire running application, threads are lightweight sub-tasks inside that process. 👉 Example: When you use WhatsApp, one thread handles message sending, another handles receiving, while another manages notifications — all at the same time. This is possible because of multithreading , which enables multiple threa...

Understanding Marker Interfaces in Java

Image
In Java, a Marker Interface is an interface that does not contain any methods or fields. It serves as a “tag” or “marker” to give special meaning to the classes that implement it. This way, the Java runtime or compiler can identify those classes and provide them with additional capabilities. 🔹 What is a Marker Interface? A marker interface is essentially an empty interface. When a class implements a marker interface, it tells the JVM that the class should be treated in a particular way. // Example of a Marker Interface public interface Serializable { // No methods or fields } public class Student implements Serializable { private int id; private String name; } Here, the Student class implements Serializable . Even though the interface is empty, the JVM knows that objects of Student can be serialized. 🔹 Popular Examples of Marker Interfaces in Java Serializable – Marks classes so their objects...