The Programmer's Guide
  • About
  • AI
  • Algorithm
    • Big O Notation
      • Tree
      • Problems
    • Basic Notes
    • Data Structure Implementation
      • Custom LinkedList
      • Custom Stack
      • Custom Queue
      • Custom Tree
        • Binary Tree Implementation
        • Binary Search Tree Implementation
        • Min Heap Implementation
        • Max Heap Implementation
        • Trie Implementation
      • Custom Graph
        • Adjacency List
        • Adjacency Matrix
        • Edge List
        • Bidirectional Search
    • Mathematical Algorithms
      • Problems - Set 1
      • Problems - Set 2
    • Bit Manipulation
      • Representation
      • Truth Tables
      • Number System
        • Java Program
      • Problems - Set 1
    • Searching
    • Sorting
    • Array Algorithms
    • String Algorithms
      • Problems - Set 1
    • Sliding Window Programming
      • Problems - Set 1
    • Tree
      • Tree Traversal Techniques
      • Tree Implementation
      • AVL Tree
      • Red-Black Trees
      • Applications of Trees
      • Problems - Set 1
    • Graph
      • Graph Traversal Techniques
      • Shortest Path Algorithms
        • Dijkstra’s Algorithm
      • Minimum Spanning Tree (MST) Algorithms
      • Topological Sort
    • Dynamic Programming
      • Problems - Set 1
    • Greedy Programming
    • Recursion
    • Parallel Programming
      • Problems - Set 1
    • Miscellaneous
      • Problems - Set 1
  • API
    • API Fundamentals
      • Terminology
      • What is an API ?
      • Consumers & Providers
      • Request & Response
      • Types of API
    • API Communication Patterns
      • Synchronous Communication
        • Request-Response Pattern (Blocking)
        • Request-Response Pattern (Non-blocking)
        • Client Polling
      • Asynchronous Communication
        • Request-Response Pattern (Truly Asynchronous)
        • Event-Driven Pattern
        • Publish-Subscribe Pattern
        • Streaming & Real-Time APIs
          • Server-Sent Events (SSE)
          • WebSockets
          • gRPC Streaming
        • Webhooks (HTTP Callbacks)
      • Hybrid or Adaptive Patterns
        • Async Requests with Sync Feedback
        • Request-Response with Async Push Updates
        • Sync-Async Failover Patterns
    • API Styles & Protocols
      • REST API
        • RESTful API Principles
        • HTTP Status Code
        • HTTP Verbs or Methods
        • HTTP Headers
          • Content Type
          • Content-Disposition
        • Query Parameters & Path Parameters
          • Handling Special Characters in URL
    • API Lifecycle Management
      • API Compatibility
        • Backward Compatibility
        • Forward Compatibility
      • API Versioning Strategies
        • REST API Versioning Approaches
        • GraphQL API Versioning Approaches
      • API Deprecation
        • REST API Deprecation Approach
    • Data Handling
      • Pagination
      • Filtering
      • Sorting
      • Field Selection (Projection)
    • Naming Guidelines
      • API Endpoint Naming
      • Parameter Naming
      • Field and Property Naming
      • Error Codes and Messages
      • Versioning Naming
    • API Testing
      • Tools
        • Postman
        • SoapUI
        • Curl
  • Database
    • DBMS
      • Types of DBMS
        • Relational DBMS (RDBMS)
        • NoSQL DBMS
        • Object-Oriented DBMS (OODBMS)
        • Columnar DBMS
        • In-Memory DBMS
        • Distributed DBMS
        • Cloud-Based DBMS
        • Hierarchical DBMS
      • DBMS Architecture
      • DBMS Structure
    • SQL Databases
      • Terminology
      • RDBMS Concepts
        • Entity Relationship Diagram (ERD)
          • ERD Examples
        • Normalization
        • Denormalization
        • ACID Properties
        • Locking and Unlocking
      • SQL Fundamentals
        • SQL Commands
          • DDL (Data Definition Language)
          • DML (Data Manipulation Language)
          • DCL (Data Control Language)
          • TCL (Transaction Control Language)
          • DQL (Data Query Language)
        • SQL Operators
          • INTERSECT
          • EXCEPT
          • MINUS
          • IN and NOT IN
          • EXISTS and NOT EXISTS
        • SQL Clauses
          • Joins
          • OVER
          • WITH
          • CONNECT BY
          • MODEL
          • FETCH FIRST
          • KEEP
          • OFFSET with FETCH
        • SQL Functions
          • Oracle Specific
        • SQL Data Types
          • Numeric Types
          • Character Types
          • Date & Time Types
          • Large Object Types
      • Vendor Specific Concepts
        • Oracle Specific
          • Data Types
            • BLOB
            • Use Case
          • Character Set
          • Rownum, Rowid, Urowid
          • Order of Execution of the query
          • Execution Plan
            • Understand Execution Plan
          • Keys
          • Tablespace
          • Partition
        • Oracle Examples
        • MYSQL Specific
          • Collation
          • Character Set
        • MYSQL Examples
      • Best Practice
      • Resources & References
        • O’Reilly SQL Cookbook (2nd Edition)
          • 1. Retrieving Records
          • 2. Sorting Query Results
          • 3. Working with Multiple Tables
          • 4. Inserting, Updating, and Deleting
          • 5. Metadata Queries
          • 6. Working with Strings
          • 7. Working with Numbers
          • 8. Date Arithmetic
          • 9. Date Manipulation
          • 10. Working with Ranges
          • 11. Advanced Searching
          • 12. Reporting and Reshaping
          • 13. Hierarchical Queries
          • 14. Odds 'n' Ends
    • NoSQL Databases
      • Concepts
        • Characteristics
        • BASE Properties
        • Eventual Consistency
        • Schema-less Design
        • Sharding
        • Partitioning
        • Transactions
        • Aggregation
        • Projections
        • CRUD Operations
      • Data Models
        • Document Store
        • Key-Value Store
        • Column-Family Store
        • Graph Database
        • Multi-Model Database
    • SQL vs NoSQL
      • ACID & BASE Properties
    • Query Concepts & Performance
      • count(1) vs count(*)
      • Access Multiple Schemas in Single Query
      • Subquery vs Joins
      • Single SQL vs PLSQL Query
  • Git
    • Commands
      • Setup and Configuration Commands
      • Getting and Creating Projects
      • Tracking Changes
      • Branching and Merging
      • Sharing and Updating Projects
      • Inspection and Comparison
      • Debugging
      • Patching
      • Stashing and Cleaning
      • Advanced Manipulations
    • Workflows
      • Branching Strategies
        • Git Flow
        • Trunk-Based Development
        • GitHub Flow
        • Comparison
      • Merge Strategies
        • Merge
        • Rebase
        • Squash
        • Fast-forward vs No-fast-forward
        • MR vs PR
      • Conflict Resolution
        • Handling Merge Conflicts
        • Merge Conflicts
        • Rebase Conflicts
        • Divergent Branches After git pull
        • Force Push
      • Patch & Recovery
        • Cherry-pick strategies
        • Revert vs Reset
        • Recover from a bad rebase
      • Rebasing Practices
        • Merge vs Rebase
        • Rebase develop branch on main branch
      • Repository Management
        • Working Directory
        • Mirror a repository
        • Convert a local folder to a Git repo
        • Backup and restore a Git repository
    • Platforms
      • GitHub
      • GitLab
        • Freeze a branch
      • Bitbucket
  • Identity and Access Management (IAM)
    • Authentication
      • Authentication Methods
    • Keycloak
      • Terminologies
      • Token Verification
      • User Federation
        • Settings
          • Provider - LDAP
        • Integrating OpenLDAP
    • LDAP
      • Local OpenLDAP Setup
    • Single Sign-On (SSO)
  • Java
    • Installation & Setup
      • Installation
      • Java Distributions
      • Java Platform Editions
        • Java SE
        • Java EE
        • Jakarta EE
        • Java ME
        • JavaFX
    • Java Evolution
      • Java Feature Introduction Process
      • Java Version History
        • Java 8
        • Java 9
      • FAQ
    • Java Basics
      • OOP Principles
        • Encapsulation
        • Inheritance
          • Method Overriding
          • Constructor Chaining
          • Dynamic Method Dispatch
          • Inheritance vs. Composition
          • Diamond Problem
        • Polymorphism
          • Rules for Polymorphism
        • Abstraction
          • Abstract Class & Method
          • Interface
            • Functional Interfaces
            • Marker Interfaces
          • Abstract Class vs Interface
          • Model as an Interface or abstract class ?
      • OOP Basics
        • What is a Class?
          • Types of Classes
        • What is an Object?
          • Equals and HashCode
            • FAQ
          • Shallow Copy and Deep Copy
          • Ways to Create Object
          • Serialization & Deserialization
        • Methods & Fields
          • Method Signature & Header
          • Method Overriding & Overloading
          • Variables
        • Constructors
        • Access Modifiers
      • Java Keywords
        • this
        • super
        • null
          • Handle Null Value
        • Access Modifiers
      • Java Data Types
        • Default Values
        • Primitive Types
          • byte
          • short
          • int
          • long
          • float
          • double
          • char
          • boolean
        • Non-Primitive (Reference) Types
          • String
            • StringBuilder
            • StringBuffer
              • Problems
            • Multiline String
            • Comparison - String, StringBuilder & StringBuffer
          • Array
          • Collections
            • List
              • Array vs List
              • ArrayList
              • Vector
                • Stack
                  • Problems
              • LinkedList
              • Examples
            • Queue
              • PriorityQueue
              • Deque (Double-Ended Queue)
                • ArrayDeque
            • Map
              • HashMap
              • Hashtable
                • Collision Resolution
              • LinkedHashMap
              • ConcurrentHashMap
              • TreeMap
              • EnumMap
              • WeakHashMap
            • Set
              • HashSet
              • LinkedHashSet
              • TreeSet
              • EnumSet
              • ConcurrentSkipListSet
              • CopyOnWriteArraySet
        • Specialized Classes
          • BigInteger
          • BigDecimal
            • Examples
          • BitSet
          • Date and Time
            • Comparison
            • Examples
          • Optional
          • Math
          • UUID
          • Scanner
          • Formatter
            • Examples
          • Properties
          • Regex (Pattern and Matcher)
            • Examples
          • Atomic Classes
          • Random
          • Format
            • NumberFormat
            • DateFormat
            • DecimalFormat
        • Others
          • Object
          • Enum
            • Pre-Defined Enum
            • Custom Enum
            • EnumSet and EnumMap
            • Enum Comparison
          • Record
          • Optional
          • System
          • Runtime
          • ProcessBuilder
          • Class
          • Void
          • Throwable
            • Error
            • Exception
              • Custom Exception Handling
              • Best Practice
            • Error vs Exception
            • StackTraceElement
      • Java Operators
        • Operator Precedence
        • Problems
      • Parallelism & Concurrency
        • Ways to Identify Thread Concurrency or Parallelism
        • Thread Fundamentals
          • Thread vs Process
          • Creating Threads
            • Runnable & Callable
            • Comparison
            • Examples
          • Thread Context Switching
          • Thread Lifecycle & States
          • Types of Threads
          • Thread Priority
          • Memory Sharing Between Threads
          • Thread Completion & JVM Exit
    • Java Internals
      • JVM Overview
        • Architecture
        • Components
        • Lifecycle
        • Command Line Arguments
      • Memory Management
        • References
        • Types of Memory
    • Java Concepts
      • Language Essentials
        • Annotation
          • Annotation Processing
          • Types of Annotations
            • Custom Annotation
              • Use Case
            • Meta Annotation
        • Generics
          • Covariance and Invariance
        • Scoped Values
        • Unnamed Variables & Patterns
      • Concurrency & Multithreading
        • Thread Management & Synchronisation
          • Thread Resource Sharing
          • Thread Synchronization
            • Why is Synchronization Needed ?
            • Synchronized Blocks & Methods
          • Thread Lock
            • Types of Locks
            • Intrinsic Lock (Monitor Lock)
            • Reentrant Lock
          • Semaphore
          • Thread Starvation
          • Thread Contention
          • Thread Deadlock
          • Best Practices for Avoiding Thread Issues
        • Executor Framework
          • ExecutorService
            • Types of Work Queues
            • Rejection Policies
            • ExecutorService Implementations
            • ExecutorService Usage
        • Asynchronous Programming
          • Future
          • CompletableFuture
          • Future v/s CompletableFuture
      • Functional Programming
        • Functional Interfaces
          • Standard Built-In Interfaces
          • Custom Interfaces
        • Streams
          • flatmap
          • Collectors Utility Class
          • Problems
      • Utilities
        • Date Time Formatter
        • Validation
        • Input Handling
        • Comparing & Ordering
          • Object Equality Check
          • Comparable and Comparator
            • Comparator Interface
          • Sorting of Objects
          • Insertion Ordering
      • Specifications & Standards
        • ISO Standards
        • JSR
          • JSR 303, 349, 380 (Bean Validation)
    • Java Packages
      • Core Packages
        • java.lang
          • java.lang.System
          • java.lang.Thread
        • java.net
          • java.net.InetAddress
        • java.nio
          • java.nio.charset
      • Jakarta Packages
        • jakarta.validation
        • javax.validation
      • Third-party Packages
    • Infrastructure & Deployment
      • Java Servers
        • Application Server
        • Web Server
        • Web Server vs Application Server
        • Server vs Container
      • Java Deployment Models
      • Build & Packaging Tools
        • Maven
    • Troubleshooting Java Code
      • Thread Dump
      • Heap Dump
      • Artifact Analysis
    • Code Quality & Analysis
      • Code Smells
        • Types of Code Smells
        • Code Smells to Avoid
      • Anti-Patterns
        • Types of Anti-Patterns
        • Cyclic dependencies
    • Code Style Guidelines
      • Naming Convention
      • Package Structure
      • Formatting
      • Comments and Documentation
      • Imports
      • Exception Handling
      • Class Structure
      • Method Guidelines
      • Lambdas and Streams Style
      • Code Style Tools
    • Java Development Tools
      • IntelliJ IDEA
        • Shortcuts for MAC
      • Apache JMeter
        • Examples
      • Thread Dump Capture
        • jstack
      • Heap Dump Capture
        • jmap
      • Wireshark
        • Search Filters
    • Best Practices
      • Method Chaining
  • Maven
    • Installation
    • Local Repository & Configuration
    • Command-line Options
    • Artifact Coordinates
      • Classifier
    • POM File
    • Build & Lifecycle
    • Dependency Management
      • Dependency
        • Transitive Dependency
        • Optional Dependency
      • Dependency Scope
        • Maven Lifecycle and Dependency Scope
      • Dependency Exclusions & Overrides
      • Bill of Materials (BOM)
      • Dependency Conflict Resolution
      • Dependency Tree & Analysis
      • Dependency Versioning Strategies
        • Artifact and BOM Versioning
    • Plugins
      • Build Lifecycle Management
      • Dependency Management
      • Code Quality and Analysis
      • Documentation Generation
      • Code Generation
      • Packaging and Deployment
      • Reporting
      • Integration and Testing
      • Customization and Enhancement
        • build-helper-maven-plugin
        • properties-maven-plugin
        • ant-run plugin
        • exec-maven-plugin
        • gmavenplus-plugin
      • Performance Optimization
    • FAQs
      • Fixing Maven SSL Issues: Unable to Find Valid Certification Path
  • Miscellaneous
    • Image
    • Mac
      • Mac Shortcuts
      • Running Oracle DB
  • Spring
    • Spring Basics
      • What is Spring ?
      • Why Use Spring
      • Spring Ecosystem
      • Versioning
      • Setting Up a Spring Project
      • Spring vs Spring Boot
    • General Concepts
      • Spring Boot Artifact Packaging
      • Classpath and Resource Loading
      • REGEX
        • Core Classes
      • Validations in Spring Framework
        • Jakarta Validation
          • Jakarta Bean Validation Annotations
    • Core Concepts
      • Spring Core
        • Dependency Injection (DI)
          • @Autowired
          • @Qualifier
          • @Primary
        • Stereotype Annotation
      • Spring Beans
        • How Spring Beans Differ from Java Beans ?
        • Bean Definition & Naming
        • Bean Lifecycle
        • Bean Scope
          • Singleton Bean
          • Use Case
        • Lazy & Eager Initialization
          • Use Case of Lazy Initialization
        • BeanFactory
        • ApplicationContext
      • Spring Profiles
      • Spring Annotations
        • Annotation Inheritance
        • Commonly Used Annotations
          • Spring Boot Specific
          • Controller Layer (Web & REST Controllers)
      • Spring Configuration
        • Custom Package Scanning
        • @Value for Property Injection
        • Mapping Properties to Java Class
    • Spring Features
      • Auto Configuration
        • Spring Boot 2: spring.factories
        • Spring Boot 3: spring.factories
      • Spring Caching
        • In-Memory Caching
      • Spring AOP
        • Before Advice
        • After Returning Advice
        • After Throwing Advice
        • After (finally) Advice
        • Around Advice
        • Use Cases
      • Spring File Handling
        • Reading a File
      • Reactive Programming
        • Reactive System
        • Reactive Stream Specification
        • Project Reactor
          • Mono & Flux
      • Asynchronous Processing
        • @Async annotation
          • Common Issues
        • ThreadPoolExecutor and Queue Management
      • Inter-Service Communication
        • REST Communication
          • 1. RestTemplate
            • Usage
            • Request Customization
            • Handling Responses
            • Exception Handling
            • Asynchronous Execution
            • Configuration
              • Configuring Request Factories
              • Types of Timeouts
            • HTTP Clients with SSL
            • OpenAPI-Generated Clients
              • Use Case: Internal API Calls with OpenAPI Clients
              • Use Case: Internal API Calls with Manual Clients
            • Transition to WebClient
          • 2. WebClient
            • Usage
            • Request Customization
            • Handling Responses
            • Exception Handling
            • Asynchronous Execution
            • Configuration
            • HTTP Clients with SSL
              • Examples
            • OpenAPI-Generated Clients
              • Use Case: Internal API Calls with OpenAPI Clients
              • Use Case: Internal API Calls with Manual Clients
          • 3. OpenFeign
            • Usage
            • Request Customization
            • Handling Responses
            • Exception Handling
            • Asynchronous Execution
            • Configuration
            • HTTP Client with SSL
            • OpenAPI-Generated Clients
              • Use Case: Internal API Calls with OpenAPI Clients
              • Use Case: Internal API Calls with Manual Clients
          • When to Use Which ?
        • Messaging Communication
          • ActiveMQ
            • Architecture Details
            • Version Overview
            • Naming Convention
            • Message Delivery Guarantee
            • Queues and Topics
            • Configuration Properties
            • Concepts
            • ActiveMQ with Spring Boot
            • Common Issues
      • Resilience Patterns
        • Retry Mechanism
          • @Retryable annotation
            • Example
      • Spring Security
        • Authentication
          • Core Components
            • Security Filter Chain
              • HttpSecurity
              • Example
            • AuthenticationManager
            • AuthenticationProvider
            • UserDetailsService
              • UserDetails
              • PasswordEncoder
            • SecurityContext
            • SecurityContextHolder
            • GrantedAuthority
            • Security Configuration (Spring Security DSL)
          • Authentication Models
            • One-Way Authentication
            • Mutual Authentication
          • Authentication Mechanism
            • Basic Authentication
            • Form-Based Authentication
            • Token-Based Authentication (JWT)
            • OAuth2 Authentication
            • Multi-Factor Authentication (MFA)
            • SAML Authentication
            • X.509 Certificate Authentication
            • API Key Authentication
            • Remember-Me Authentication
            • Custom Authentication
          • Logout Handling
        • Authorization
        • Security Filters and Interceptors
        • CSRF
          • Real-World CSRF Attacks & Prevention
        • CORS
        • Session Management and Security
        • Best Practices
      • Spring Persistence
        • JDBC
          • JDBC Components
          • JDBC Template
          • Transaction Management
          • Best Practices in JDBC Usage
          • Datasource
            • Connection Pooling
              • HikariCP
            • Caching
        • JPA (Java Persistence API)
          • JPA Fundamentals
          • ORM Mapping Annotations
            • 1. Entity and Table Mappings
            • 2. Field/Column Mappings
            • 3. Relationship Mappings
            • 4. Inheritance Mappings
            • 5. Additional Configuration Annotations
          • Querying Data
            • JPQL
            • Criteria API
            • JPA Specification
              • Example - Employee Portal
            • Native SQL Queries
            • Named Queries
            • Query Return Types
            • Pagination & Sorting
              • Example - Employee Portal
            • Projection
          • Fetch Strategies in JPA
        • JPA Implementation
          • Hibernate
            • SQL AST
            • Properties
            • CRUD API Using Hibernate
        • Spring Data JPA
          • Repository Abstractions
          • Entity-to-Table Mapping
          • Derived Query Methods
        • Cross-Cutting Concerns
          • Transactions
          • Caching
          • Concurrency
        • Common Issues
          • Dead Lock
        • Liquibase
          • Installation & Setup
          • Change Tracking & Locking
          • Liquibase with Spring Boot
          • Liquibase CLI
          • Use Case
        • Examples
          • Employee Portal
            • API
      • Spring Scheduling
        • Cron Expression
        • Distributed Scheduling
          • ShedLock
      • Thymeleaf Integration
    • Security & Data Protection
      • Encoding | Decoding
        • Base Encoding
          • Base32
            • Encoding and Decoding in Java
        • Text Encoding
          • Extended ASCII
          • ASCII
            • Encoding and Decoding in Java
        • Base Encoding Decoding Examples
        • Text Encoding Decoding Examples
        • Best Practices and Concepts
      • Cryptography
        • Terminology
        • Java Cryptography Architecture (JCA)
        • Key Management
          • Key Generation
            • Tools and Libraries
              • OpenSSL
              • Java Keytool
                • Concept
                • Use Cases
            • Key & Certificate File Formats
          • Key Distribution
          • Key Storage
          • Key Rotation
          • Key Revocation
        • Encryption & Decryption
          • Symmetric Encryption
            • Algorithm
            • Modes of Operation
            • Examples
          • Asymmetric Encryption
            • Algorithm
            • Mode of Operation
            • Examples
        • MAC & HMAC
        • KDF
          • Salt & Nonce
        • Pseudorandom Number Generators (PRNGs)
    • Utilities & Libraries
      • Jackson ObjectMapper
      • Apache Libraries
        • Apache Camel
          • Camel Architecture
            • Camel Context
            • Camel Endpoints
            • Camel Components
            • Camel Exchange & MEP
          • Spring Dependency
          • Different Components
            • Camel SFTP
        • Apache Commons Lang
          • StringUtils
          • ArrayUtils
          • NumberUtils
          • SystemUtils
          • RandomStringUtils
          • DateUtils
          • EqualsBuilder & HashCodeBuilder
          • StopWatch
        • Apache Commons IO
          • FileUtils
        • Apache Commons Validator
      • MapStruct Mapper
      • Lombok
        • Logging with Lombok
      • Utilities by Spring framework
        • StopWatch
      • ArchUnit
    • Deployment & Packaging
      • Inspecting Docker Images
    • Microservices
      • Load Balancing
        • Client-Side Load Balancing Example
        • Server-Side Load Balancing Example
    • Practical Guidelines
      • Spring Coding Conventions
        • Layered Architecture Rules
        • Package & Class Location Rules
        • Dependency Rules
        • Naming Convention Rules
        • Annotation Usage Rules
        • Forbidden API Usage Rules
        • Dependency Cycle Rules
        • Test Layer Rules
        • Documentation & Logging Rules
      • Spring Configuration
      • Spring Code Design
  • Software Testing
    • Testing Fundamentals
      • Software Testing Methodologies
        • Functional Testing
          • Unit Testing
            • Scenario Matrix Template
          • Integration Testing
            • Scenario Matrix Template
          • System Testing
            • Scenario Matrix Template
          • Acceptance Testing
            • Scenario Matrix Template
        • Non Functional Testing
          • Performance Testing
            • Load Testing
              • Terminology
              • Process
              • Strategy
              • Preparation Checklist
              • Metrics to Measure
              • Scenario Matrix Template
            • Stress Testing
              • Scenario Matrix Template
            • Spike Testing
              • Scenario Matrix Template
            • Soak Testing
              • Scenario Matrix Template
            • Scalability Testing
              • Scenario Matrix Template
          • Security Testing
            • Scenario Matrix Template
          • Usability Testing
            • Scenario Matrix Template
          • Reliability Testing
            • Scenario Matrix Template
          • Compatibility Testing
            • Scenario Matrix Template
          • Maintainability Testing
            • Scenario Matrix Template
          • Portability Testing
            • Scenario Matrix Template
          • Recovery Testing
            • Scenario Matrix Template
          • Compliance Testing
            • Scenario Matrix Template
          • Localization Testing
            • Scenario Matrix Template
      • Software Testing Life Cycle (STLC)
    • Levels of Testing
    • Java Test Framework
      • JUnit
        • JUnit 4
        • JUnit 5
          • Parameterized Test
          • Single and Multiple Assertions
        • JUnit 4 vs JUnit 5
      • MockServer
    • Test Automation
      • Manual vs Automated Testing
      • Test Automation Strategies
      • CI/CD Integration
  • System Design
    • Design Foundations
      • Programming Paradigms
      • System Characteristics
      • Object-Oriented Design
        • SOLID Principles
        • GRASP Principles
        • Composition
        • Aggregation
        • Association
      • Design Thinking & Process
        • Problem Framing
        • Use Case Analysis
        • Requirements Gathering
        • Iterative Design Process
      • Workload Types
    • Design Principles & Patterns
      • Software Design Principles
        • DRY
        • KISS
        • YAGNI
        • Separation of Concerns
        • Encapsulation & Abstraction
        • Modularity & Reusability
      • Design Pattern
        • Creational Pattern
        • Structural Pattern
        • Behavioral Pattern
        • Examples
          • Data Collector
          • Payment Processor
          • Transaction Dispute
          • Payment Validation
        • Design Enhancements
          • Fluent API Design
            • Examples
      • Design Metrics
        • Coupling
        • Cohesion
        • Cyclomatic Complexity
        • Lines of Code (LOC)
        • Halstead Metrics
        • Maintainability Index
    • System Design Methodology
      • Design Layers
        • Low-Level Design (LLD)
        • High-Level Design (HLD)
      • Design Diagrams
        • UML Diagrams
          • PlantUML
            • Class Diagram
            • Object Diagram
            • Sequence Diagram
            • Use Case Diagram
            • Activity Diagram
            • State Diagram
            • Architecture Diagram
            • Component Diagram
            • Timing Diagram
            • ER Diagram (Entity-Relationship)
            • Network Diagram
    • Architectural Styles
      • System-Level
        • Monolith
        • Microservices
        • Event Driven Architecture
        • Serverless
      • Application-Level
        • Layered Architecture
        • Hexagonal Architecture
        • Clean Architecture
      • How System-Level and Application-Level Work Together ?
      • Trends in Practice
        • Spring Boot Microservice with Clean Architecture
        • Spring Boot Microservice with Hexagonal Architecture
    • Architecture Principles
      • Twelve-Factor App Principles
      • Cloud-Native Principles
      • Reactive Manifesto
      • Infrastructure as Code (IaC)
      • DevOps Principles
      • Design for Failure
      • CAP Theorem
    • Architectural Building Blocks
      • Load Balancer
        • Load Balancer Architecture
        • Load Balancer Monitoring Tool
      • Caching
        • Pod-Level vs Distributed Caching
    • Scalability & Reliability
      • Scaling
        • Vertical Scaling (Scaling Up)
        • Horizontal Scaling (Scaling Out)
        • Auto-Scaling
        • Database Scaling via Sharding
      • Resilience & Failure Handling
    • Delivery & Deployment Strategy
      • Feature Flags
      • Traffic Shifting
      • Deployment Patterns
    • Observability
      • Distributed Tracing
        • Fundamentals
        • Tracing Modes
    • Data Handling & Processing
      • MapReduce
        • Example
    • Performance Engineering
      • Why Is My API Sometimes Slow ?
      • Networking Metrics
        • Types of Delay
        • Scenario
    • Security
      • Security Principles
        • CIA
        • Least Privilege Principle
        • Defense in Depth
        • Zero Trust Security Model
        • Security by Design
        • Zero Trust Architecture
      • Security Threats & Mitigations
        • OWASP
          • Top 10 Security Threats
          • Application Security Verification Standard
          • Software Assurance Maturity Model
          • Dependency Check
          • CSRFGuard
          • Cheat Sheets
          • Security Testing Guide
          • Threat Dragon
        • Threat Modeling
        • Cyber Attacks
      • Application-Level Security
        • CORS (Cross-Origin Resource Sharing)
      • Secure Software Development Lifecycle
        • Secure Coding Practices
        • DevSecOps
      • Compliance & Regulation
        • GDPR
        • PCI DSS
    • Operational Issues
      • Common Runtime Errors
        • OOM: Unable to Create Native Thread
        • OOM: Requested array size exceeds VM limit
  • Interview Guide
    • Non-Technical
      • Behavioural or Introductory Guide
      • Project Specific
    • Technical
      • Java Interview Companion
        • Java Key Concepts
          • Set 1
          • Set 2
          • Set 3
        • Java Code Snippets
        • Java Practice Programs
          • Set 3 - Strings
          • Set 4 - Search
          • Set 5 - Streams and Collection
      • SQL Interview Companion
        • SQL Practice Problems
          • Set 1
      • Spring Interview Companion
        • Spring Key Concepts
          • Set 1 - General
          • Set 2 - Core Spring
        • Spring Code Snippets
          • JPA
      • Application Server
      • Maven
      • Containerized Application
      • Microservices
    • General
      • Applicant Tracking System (ATS)
      • Flowchart - How to Solve Coding Problem?
Powered by GitBook
On this page
  1. Algorithm

Tree

PreviousProblems - Set 1NextTree Traversal Techniques

Last updated 6 months ago

CtrlK
  • About Tree Data Structure
  • What is a Tree?
  • Basic Terminologies
  • Example
  • Examples of Trees
  • Tree Height, Depth & Breadth
  • 1. Height of a Tree
  • 2. Depth of a Node
  • 3. Breadth of a Tree
  • Balanced and Unbalanced Tree
  • 1. What is a Balanced Tree?
  • 2. What is an Unbalanced Tree?
  • 3. Why Should a Tree Be Balanced?
  • Types of Trees in Data Structures
  • 1. General Tree
  • 2. Binary Tree
  • 3. Binary Search Tree (BST)
  • 4. AVL Tree (Self-Balancing BST)
  • 5. Red-Black Tree
  • 6. B-Trees & B+ Trees
  • 7. Trie (Prefix Tree)
  • 8. Segment Tree
  • 9. Fenwick Tree (Binary Indexed Tree - BIT)
  • 10. Heap (Min Heap, Max Heap)
  • 11. Suffix Tree
  • Comparisons of Tree Types

About Tree Data Structure

A Tree is a non-linear data structure used to represent hierarchical relationships between elements. It consists of nodes connectedT by edges, with one node designated as the root. Unlike arrays, stacks, or linked lists, which store data sequentially, trees are structured to allow for efficient searching, insertion, and deletion operations.

Trees are fundamental in various computing applications, including databases, networking, artificial intelligence, and file systems. They provide fast lookups, efficient sorting mechanisms, and optimized memory usage for hierarchical data storage.

What is a Tree?

A Tree is a hierarchical data structure that consists of nodes connected by edges. It has the following key characteristics:

  1. Root Node: The topmost node in the hierarchy.

  2. Parent-Child Relationship: Each node can have multiple child nodes, but only one parent (except the root, which has no parent).

  3. Leaf Nodes: Nodes that do not have any children.

  4. Height of a Tree: The longest path from the root to any leaf.

  5. Depth of a Node: The distance from the root to that node.

Basic Terminologies

Term
Description

Node

A single element in the tree.

Edge

The connection between two nodes.

Root

The topmost node of the tree.

Parent

A node that has one or more child nodes.

Child

A node that has a parent.

Sibling

Nodes that share the same parent.

Leaf

A node that has no children.

Degree

The number of child nodes a node has.

Height

The longest path from a node to a leaf node.

Depth

The distance from the root node to a specific node.

Breadth

The breadth of a tree refers to the maximum number of nodes present at any level in the tree.

Example

                             (Root) A
                          /            \
                (Parent) B                C (Parent)
                /      \                   /   \  
        (Parent) D      E (Leaf)   (Parent) F   G (Leaf)
          /   |  \  \                 /  |   \
   (Leaf) H   I   J   K (Leaf)       L   M  (Leaf) N  
              |
       (Leaf) O

Root (A) → The topmost node of the tree.
Parent (B, C, D, F) → Nodes that have one or more children.
Child (B, C are children of A, etc.) → Nodes connected below a parent.
Sibling (B and C, D and E, F and G, etc.) → Nodes with the same parent.
Leaf (E, G, H, K, M, N, O) → Nodes with no children.
Internal Node (B, C, D, F) → Nodes that are neither root nor leaves.

Subtree:
The subtree rooted at D contains {D, H, I, J, K, O}.
The subtree rooted at F contains {F, L, M, N}.

Depth of a Node → Distance from the root:
Depth of A = 0
Depth of B, C = 1
Depth of D, E, F, G = 2
Depth of H, I, J, K, L, M, N = 3
Depth of O = 4

Height of a Tree → Longest path from root to leaf (Here, height = 4).

Breadth
Level 0 →  A  → 1 node
Level 1 →  B, C  → 2 nodes
Level 2 →  D, E, F, G  → 4 nodes
Level 3 →  H, I, J, K, L, M, N  → 7 nodes
Level 4 →  O  → 1 node
The maximum number of nodes at any level is 7 (at level 3).
Breadth of this tree = 7.

Examples of Trees

Trees are widely used in real-world applications due to their hierarchical nature. Here are some practical examples:

1. File System Hierarchy

The file system in an operating system is organized as a tree:

Root Directory
│
├── Folder1
│   ├── File1
│   ├── File2
│
├── Folder2
│   ├── SubFolder1
│   │   ├── File3
│   │   ├── File4

Each directory is a node, and files or subdirectories are children.

2. Organization Charts

A company’s hierarchy is represented as a tree:

CEO
│
├── VP of Engineering
│   ├── Software Engineer
│   ├── QA Engineer
│
├── VP of Sales
│   ├── Sales Manager
│   ├── Sales Representative

This helps in structuring teams and workflow.

Tree Height, Depth & Breadth

1. Height of a Tree

The height of a tree is defined as the length of the longest path from the root node to a leaf node. It represents the maximum number of edges from the root to any leaf.

  • Root node height = The height of the entire tree.

  • Leaf node height = Always 0, as there are no children below it.

How to Calculate the Height of a Tree?

  1. Start at the root node.

  2. Recursively find the height of all child subtrees.

  3. The height of the tree is 1 + max(height of all child subtrees).

  4. If the tree has no nodes, the height is -1 (for edge-based height) or 0 (for node-based height).

Example:

       A
      / \
     B   C
    /   / \
   D   E   F
  /
 G
  • G is a leaf node → Height = 0

  • D has one child G → Height = 1

  • B has one child D → Height = 2

  • E and F are leaves → Height = 0

  • C has two children E and F → Height = 1

  • A (root) has two children B (Height 2) and C (Height 1) → Height = 3

Thus, Height of Tree = 3.

2. Depth of a Node

The depth of a node is the number of edges from the root to that node.

  • Root node depth = Always 0.

  • Child node depth = 1 + depth of its parent.

How to Calculate the Depth of a Node?

  1. Start at the root node (depth = 0).

  2. Move down the tree, increasing depth by 1 at each level.

  3. The depth of a node is the number of edges from the root to that node.

Example:

mathematicaCopyEdit       A (Depth 0)
      / \
     B   C  (Depth 1)
    /   / \
   D   E   F  (Depth 2)
  /
 G  (Depth 3)
  • Depth(A) = 0 (root node)

  • Depth(B) = 1, Depth(C) = 1 (children of A)

  • Depth(D) = 2, Depth(E) = 2, Depth(F) = 2 (children of B and C)

  • Depth(G) = 3 (child of D)

Edge-Based vs. Node-Based Height

  • Edge-Based Height: The number of edges in the longest path to a leaf (common in CS).

  • Node-Based Height: The number of nodes in the longest path (sometimes used in theoretical problems).

For a tree with a single node,

  • Edge-Based Height = -1

  • Node-Based Height = 0

3. Breadth of a Tree

The breadth of a tree is the maximum number of nodes at any level.

For example:

       A
      / \
     B   C
    /   / \
   D   E   F
  /
 G
  • Level 0: A → 1 node

  • Level 1: B, C → 2 nodes

  • Level 2: D, E, F → 3 nodes (maximum)

  • Level 3: G → 1 node

Breadth of this tree = 3 (since level 2 has the most nodes).

Balanced and Unbalanced Tree

1. What is a Balanced Tree?

A Balanced Tree is a tree in which the height difference between the left and right subtrees of any node is at most 1. This ensures that the tree remains efficient for operations like searching, inserting, and deleting.

Characteristics of a Balanced Tree:

  • The difference in height (Balance Factor) between the left and right subtrees of every node is at most 1.

  • Searching, inserting, and deleting operations run in O(log N) time.

  • Prevents the tree from becoming too deep and inefficient.

Examples of Balanced Trees:

  • AVL Tree: Self-balancing binary search tree where balance factor is maintained between -1 and 1.

  • Red-Black Tree: A balanced binary search tree used in many libraries (e.g., TreeMap in Java).

  • B-Trees & B+ Trees: Used in databases for indexing.

  • Heap (Min Heap / Max Heap): Ensures a balanced structure to maintain efficient extraction of min/max.

  • The height difference between left and right subtrees for every node is ≤1.

  • Height = log(N) → Searching is efficient.

Example of a Balanced Tree

        10
       /  \
      5    15
     / \   /  \
    2   7 12  18
   / \     \
  1   3     13

Balance Factor Calculation

All nodes have balance factors between -1 and 1, so this tree is balanced.

Node

Left Subtree Height

Right Subtree Height

Balance Factor (Left - Right)

10

3

3

0

5

2

2

0

15

1

2

-1

2

1

1

0

7

0

1

-1

12

0

1

-1

18

0

0

0

2. What is an Unbalanced Tree?

An Unbalanced Tree is a tree in which the height difference between the left and right subtrees is greater than 1, leading to inefficiencies in operations.

Characteristics of an Unbalanced Tree:

  • The height of one subtree is much greater than the other.

  • Searching, inserting, and deleting operations can take O(N) time instead of O(log N).

  • The tree resembles a linked list in extreme cases (degenerate tree).

  • The height of the tree is N instead of log(N).

  • Searching for 4 requires O(N) operations instead of O(log N).

Examples of Unbalanced Trees:

  • Skewed Binary Tree: All nodes are aligned to one side.

  • Degenerate Tree: Every node has only one child, forming a linked list.

Example of an Unbalanced Tree (Right-Skewed):

       1
        \
         2
          \
           3
            \
             4

Example of an Unbalanced Tree (Without Being Skewed)

        10
       /  \
      5    15
     / \      \
    2   7      18
   /            \
  1              20

Balance Factor Calculation

  • Node 15 has a balance factor of -2, making the tree unbalanced.

  • Although the left subtree of 10 is balanced, the right subtree is too deep.

  • Searching for 20 would take longer than expected.

Node

Left Subtree Height

Right Subtree Height

Balance Factor (Left - Right)

10

2

3

-1 (Balanced)

5

2

1

1 (Balanced)

15

0

2

-2 (Unbalanced) X

2

1

0

1 (Balanced)

7

0

0

0 (Balanced)

18

0

1

-1 (Balanced)

1

0

0

0 (Balanced)

20

0

0

0 (Balanced)

3. Why Should a Tree Be Balanced?

  • Ensures Fast Operations: A balanced tree guarantees that operations like searching, inserting, and deleting run in O(log N) time.

  • Prevents Performance Degradation: An unbalanced tree degenerates into a linked list, leading to inefficient operations.

  • Used in Many Real-World Applications: Databases (B-Trees), Memory Management (Heap), and File Systems (Trie) rely on balanced trees.

Types of Trees in Data Structures

1. General Tree

  • A tree where each node can have any number of children.

  • Used in hierarchical structures like file systems, organization charts, etc.

  • Height: Maximum depth of the tree.

  • Breadth: Maximum number of nodes at any level.

2. Binary Tree

  • Each node has at most two children: left and right.

  • Types of binary trees include:

    • Full Binary Tree

    • Complete Binary Tree

    • Perfect Binary Tree

    • Balanced Binary Tree

    • Degenerate Tree

  • Height: At most O(n) for an unbalanced tree, O(log n) for balanced trees.

  • Depth: Varies depending on the structure.

2.1. Full Binary Tree

  • A binary tree where every node has either 0 or 2 children (no nodes with only one child).

  • Height: h=O(log⁡n)

  • Breadth: Maximum at the last level.

         A
       /   \
      B     C
     / \   / \
    D   E F   G

2.2. Complete Binary Tree

  • A binary tree where all levels except the last are completely filled, and nodes in the last level are as left as possible.

  • Example: Heap data structures follow this rule.

  • Height: O(log⁡n)

  • Breadth: Maximum at last level 2^(h−1)

         A
       /   \
      B     C
     / \   /
    D   E F  

2.3. Perfect Binary Tree

  • A binary tree where all levels are fully filled.

  • Number of nodes at depth d is 2^d.

  • Height: h=log⁡(n+1)−1 (log with base 2)

  • Breadth: 2^(h−1) (maximum nodes at last level).

         A
       /   \
      B     C
     / \   / \
    D   E F   G

2.4. Balanced Binary Tree

  • A binary tree where the height of left and right subtrees differs by at most 1.

  • Example: AVL Tree, Red-Black Tree.

  • Height: O(log⁡n).

  • Breadth: Maximum at last level.

         A
       /   \
      B     C
     / \   / \
    D   E F   G

2.5. Degenerate (Skewed Tree)

  • A linked list-like structure, where each node has only one child.

  • Height: O(n)(worst case).

  • Breadth: Always 1.

    A
     \
      B
       \
        C
         \
          D

3. Binary Search Tree (BST)

A Binary Search Tree (BST) is a binary tree in which:

  • Each node has at most two children (left and right).

  • The left subtree contains only nodes with values smaller than the parent node.

  • The right subtree contains only nodes with values greater than the parent node.

  • The left and right subtrees must also be BSTs.

  • Used for efficient searching.

  • Height: O(log⁡n) (balanced), O(n) (worst case).

Example of a BST

        10
       /  \
      5    15
     / \   /  \
    2   7 12  20

BST Property Holds:

  • Left subtree of 10 → {5, 2, 7} (All values < 10)

  • Right subtree of 10 → {15, 12, 20} (All values > 10)

  • This rule applies to all nodes recursively.

A Non-Binary Search Tree is any tree that does not follow the BST property. It can be:

  1. A Binary Tree that does not maintain BST ordering.

  2. A tree that is not even binary (i.e., nodes have more than two children).

Example of a Non-Binary Search Tree (Binary but not BST)

        10
       /  \
      5    15
     / \   /  \
    12  2 7   20

Not a BST because:

  • The left subtree of 5 contains 12, but 12 > 5

  • The right subtree of 15 contains 7, but 7 < 15

This is not a BST, even though it is a binary tree.

Example of a Non-Binary Search Tree (Non-Binary)

A General Tree where each node can have more than two children:

        A
       /|\
      B C D
     / \   \
    E   F   G

Not a BST because:

  • More than two children per node

  • No strict left < parent < right rule

This is an n-ary tree and does not qualify as a BST.

4. AVL Tree (Self-Balancing BST)

  • A BST with a balance factor (height difference of left and right subtree is at most 1).

  • Height: O(log⁡n).

  • Used for fast lookups.

        8
       /  \
      4    12
     / \   /  \
    2   6 10  14

5. Red-Black Tree

  • A self-balancing BST with the following rules:

    • Nodes are either Red or Black.

    • Root is always black.

    • Red nodes cannot be consecutive.

    • All paths from root to leaves have the same number of black nodes.

  • Height: O(log⁡n)

6. B-Trees & B+ Trees

  • B-Tree: A self-balancing multi-way tree (used in databases).

  • B+ Tree: Variation of B-tree where all values are stored in leaf nodes (used in file systems).

  • Height: O(log⁡n)

7. Trie (Prefix Tree)

A Trie (pronounced "try") is a tree-based data structure used to store strings efficiently for fast retrieval. It is also called a prefix tree because all common prefixes are shared among words.

Features of a Trie:

  • Each node represents a character in a string.

  • The root node represents an empty string.

  • Each path from the root to a leaf forms a word.

  • Efficient for prefix-based searching, autocomplete, and dictionary implementations.

Structure of a Trie

A Trie consists of:

  1. Nodes – Each node contains:

    • A character

    • A list of child nodes (pointers to next characters)

    • A flag to mark the end of a word

  2. Edges – Represent connections between characters.

Example of a Trie storing "car", "cat", "bat", and "bar":

        (root)
       /     \
      b       c
     / \      |
    a   a     a
   /     \    |
  r       t   r
              |
              t  

Words Stored: "car", "cat", "bat", "bar" Common Prefixes are Shared: "ca" is shared between "car" and "cat".

8. Segment Tree

  • A tree used for range queries and updates (sum, min, max).

  • Height: O(log⁡n).

  • Example: Finding the sum of elements in an array from index 2 to 5.

9. Fenwick Tree (Binary Indexed Tree - BIT)

  • A more space-efficient version of a segment tree.

  • Used for fast prefix sum calculations.

  • Height: O(log⁡n)

10. Heap (Min Heap, Max Heap)

A Heap is a specialized tree-based data structure that satisfies the Heap Property. It is commonly used for priority queues, scheduling algorithms, and efficient sorting techniques (Heap Sort).

1. What is a Heap?

A Heap is a complete binary tree (every level is fully filled except possibly the last level, which is filled from left to right) that satisfies one of the following properties:

  1. Min Heap Property → The parent node is always smaller than its children.

  2. Max Heap Property → The parent node is always greater than its children.

2. Min Heap

A Min Heap is a binary tree where:

  • The root node is the smallest element in the tree.

  • Every parent node has a value smaller than or equal to its children.

  • The smallest element is always at the root.

Example of a Min Heap

         2
       /   \
      5     7
     / \   / \
    10  15 17 25

Min Heap Property Holds:

  • 2 < 5, 2 < 7 (Root is smallest)

  • 5 < 10, 5 < 15, 7 < 17, 7 < 25

Operations in Min Heap

Operation

Time Complexity

Insertion

O(log N)

Deletion (extract min)

O(log N)

Heapify (convert array to heap)

O(N)

Find Min

O(1) (always the root)

3. Max Heap

A Max Heap is a binary tree where:

  • The root node is the largest element in the tree.

  • Every parent node has a value greater than or equal to its children.

  • The largest element is always at the root.

Example of a Max Heap

         25
       /    \
      17     10
     /  \   /  \
    7   5  2   15

Max Heap Property Holds:

  • 25 > 17, 25 > 10 (Root is largest)

  • 17 > 7, 17 > 5, 10 > 2, 10 > 15

Operations in Max Heap

Operation

Time Complexity

Insertion

O(log N)

Deletion (extract max)

O(log N)

Heapify (convert array to heap)

O(N)

Find Max

O(1) (always the root)

11. Suffix Tree

  • A compressed Trie used for string matching.

  • Height: O(m).

  • Used in bioinformatics, search engines.

Comparisons of Tree Types

Tree Type
Structure
Height
Breadth
Use Case

General Tree

Any number of children

O(n)

O(n)

Hierarchical data

Binary Tree

At most 2 children

O(n)

O(n)

Basic tree structure

BST

Sorted Binary Tree

O(log n)

O(log n)

Searching

AVL Tree

Self-balancing BST

O(log n)

O(log n)

Fast lookups

Red-Black Tree

Self-balancing BST

O(log n)

O(log n)

Efficient insertions

Trie

Prefix-based

O(m)

O(n)

Autocomplete, dictionaries

Segment Tree

Interval-based

O(log n)

O(log n)

Range queries

Heap

Complete Binary Tree

O(log n)

O(2^h)

Priority Queues