{"id":27019371,"url":"https://github.com/ahadalireach/dsa.concepts.interview.questions","last_synced_at":"2026-01-19T04:01:46.165Z","repository":{"id":280460266,"uuid":"941370595","full_name":"ahadalireach/dsa.concepts.interview.questions","owner":"ahadalireach","description":"A repository containing DSA concepts with interview questions and code implementations.","archived":false,"fork":false,"pushed_at":"2025-03-22T15:20:17.000Z","size":114,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-04-04T17:33:40.748Z","etag":null,"topics":["ds","dsa","dsa-cpp","dsa-notes","dsa-questions"],"latest_commit_sha":null,"homepage":"https://github.com/ahadalireach/dsa.concepts.interview.questions","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ahadalireach.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2025-03-02T05:50:48.000Z","updated_at":"2025-03-22T15:20:21.000Z","dependencies_parsed_at":"2025-03-03T15:37:31.742Z","dependency_job_id":"ae5c730d-f15e-4d59-ac32-b0de1e75389d","html_url":"https://github.com/ahadalireach/dsa.concepts.interview.questions","commit_stats":null,"previous_names":["ahadalireach/dsa.concepts.interview.questions"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/ahadalireach/dsa.concepts.interview.questions","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ahadalireach%2Fdsa.concepts.interview.questions","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ahadalireach%2Fdsa.concepts.interview.questions/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ahadalireach%2Fdsa.concepts.interview.questions/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ahadalireach%2Fdsa.concepts.interview.questions/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ahadalireach","download_url":"https://codeload.github.com/ahadalireach/dsa.concepts.interview.questions/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ahadalireach%2Fdsa.concepts.interview.questions/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28561603,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-19T03:31:16.861Z","status":"ssl_error","status_checked_at":"2026-01-19T03:31:15.069Z","response_time":67,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ds","dsa","dsa-cpp","dsa-notes","dsa-questions"],"created_at":"2025-04-04T17:27:19.479Z","updated_at":"2026-01-19T04:01:46.145Z","avatar_url":"https://github.com/ahadalireach.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# Data Structures and Algorithms (DSA) - Concepts \u0026 Interview Questions\n\n## \u003ca id=\"table-of-contents\"\u003e\u003c/a\u003eTable of Contents\n\n## Introduction to DSA\n\n| No. | Questions |\n| --- | ----------------------------------------------------------------- |\n| 1   | [What is Data Structure?](#what-is-data-structure) |\n| 2   | [How is Data Organized in Memory?](#how-is-data-organized-in-memory) |\n| 3   | [Stack vs Heap Memory](#stack-vs-heap-memory) |\n| 4   | [Types of Data Structures](#types-of-data-structures) |\n| 5   | [Time and Space Complexity](#time-and-space-complexity) |\n\n---\n---\n\n## Array Representations\n\n| No. | Questions |\n| --- | ----------------------------------------------------------------- |\n| 1   | [What is an Array?](#what-is-an-array) |\n| 2   | [What are Dynamic Arrays?](#what-are-dynamic-arrays) |\n| 3   | [What are Static Arrays?](#what-are-static-arrays) |\n| 4   | [What is a 2D Array?](#what-is-a-2d-array) |\n| 5   | [What defines the Dimensionality of an array?](#what-defines-the-dimensionality-of-an-array) |\n| 6   | [Advantages and Disadvantages of Arrays](#advantages-and-disadvantages-of-arrays) |\n\n---\n---\n\n## Array as ADT (Abstract Data Type)\n\n| No. | Questions |\n| --- | ----------------------------------------------------------------- |\n| 1   | [What does it mean by Array ADT?](#what-does-it-mean-by-array-adt) |\n| 2   | [How to Add / Append?](#how-to-add-append) |\n| 3   | [How to Insert?](#how-to-insert) |\n| 4   | [How to Delete?](#how-to-delete) |\n| 5   | [How to Search?](#how-to-search) |\n| 6   | [What is Linear Search?](#what-is-linear-search) |\n| 7   | [How to improve Linear Search (Move to Head / Move to Front)?](#how-to-improve-linear-search-move-to-head-move-to-front) |\n| 8  | [What is Binary Search?](#what-is-binary-search) |\n| 9  | [Difference between Linear and Binary Search?](#difference-between-linear-and-binary-search) |\n| 10  | [How to Get, Set, Find Min - Max?](#how-to-get-set-find-min-max) |\n| 11  | [How to Reverse and Shift an Array?](#how-to-reverse-and-shift-an-array) |\n| 12  | [Left Shift / Rotation?](#left-shift-rotation) |\n| 13  | [Right Shift / Rotation?](#right-shift-rotation) |\n| 14  | [Insert into Sorted Array?](#insert-into-sorted-array) |\n| 15  | [Check if an Array is Sorted?](#check-if-an-array-is-sorted) |\n| 16  | [Arranging Negative Numbers on Left Side?](#arranging-negative-numbers-on-left-side) |\n| 17  | [Merge Arrays?](#merge-arrays) |\n| 18  | [Set Operations (Union, Intersection, Difference)?](#set-operations-union-intersection-difference) |\n| 19  | [Find Missing Element (Single Missing, Multiple Missing)?](#find-missing-element-single-missing-multiple-missing) |\n| 20  | [Find Duplicate Elements?](#find-duplicate-elements) |\n| 21  | [Finding a Pair with Sum K?](#finding-a-pair-with-sum-k) |\n| 22  | [Reverse an Array?](#reverse-an-array) |\n| 23  | [Find Two Elements with Difference Equal to S in a Sorted Array?](#find-two-elements-with-difference-equal-to-s-in-a-sorted-array) |\n| 24 | [Finding Minimum and Maximum in a Single Scan?](#finding-minimum-and-maximum-in-a-single-scan) |\n| 25  | [Find Array Elements that are Neither Minimum nor Maximum?](#find-array-elements-that-are-neither-minimum-nor-maximum) |\n| 26  | [Find 2nd Maximum or Minimum Element?](#find-2nd-maximum-or-minimum-element) |\n| 27  | [Find Elements in Range (0-100) with Frequency \u003e 50](#find-elements-in-range-0-100-with-frequency--50) |\n\n---\n---\n\n## Strings\n\n| No. | Questions |\n| --- | ----------------------------------------------------------------- |\n| 1   | [What is character set?](#character-set) |\n| 2   | [What is the ASCII of strings?](#ascii) |\n| 3   | [What is string?](#strings) |\n| 4   | [Difference b/w character set and strings?](#difference-between-character-set-and-strings) |\n| 5   | [How to find Length of string?](#how-to-find-length-of-string) |\n| 6   | [How to change case of strings?](#how-to-change-case-of-strings) |\n| 7   | [How to count words, vowels and consonants in a string?](#how-to-count-words-vowels-and-consonants-in-a-string) |\n| 8   | [How to validate a string?](#how-to-validate-a-string) |\n| 9   | [How to reverse a string?](#how-to-reverse-a-string) |\n| 10  | [How to compare strings and check palindrome?](#how-to-compare-strings-and-check-palindrome) |\n| 11  | [How to find duplicates in strings?](#how-to-find-duplicates-in-strings) |\n| 12  | [How to apply bitwise operations?](#how-to-apply-bitwise-operations) |\n| 13  | [How to check if strings are anagram?](#how-to-check-if-strings-are-anagram) |\n| 14  | [How to find permutation of strings?](#how-to-find-permutation-of-strings) |\n\n---\n---\n\n## Recursion\n\n| No. | Questions |\n| --- | ----------------------------------------------------------------- |\n| 1.  | [What is Recursion?](#what-is-recursion) |\n| 2.  | [How Recursion Works?](#how-recursion-works) |\n| 3.  | [What are the Advantages \u0026 Disadvantages of Recursion?](#advantages--disadvantages-of-recursion) |\n| 4.  | [How to Trace Recursive Functions?](#tracing-recursive-functions) |\n| 5.  | [What are the Phases of Recursion?](#calling--returning-phases) |\n| 6.  | [What is the Difference Between Recursion and Loop?](#recursion-vs-loop) |\n| 7.  | [How Recursion Uses Stack?](#how-recursion-uses-stack) |\n| 8.  | [What are the Types of Recursion?](#types-of-recursion) |\n| 9.  | [What is the Time Complexity of Recursion (Tree vs Recurrence Relation)?](#time-complexity-of-recursion) |\n| 10. | [What are the Steps to Solve Recursive Problems?](#steps-to-solve-recursive-problems) |\n| 11. | [How to find the Sum of First N Natural Numbers?](#sum-of-first-n-natural-numbers) |\n| 12. | [How to find the Factorial of a Number?](#factorial-of-a-number) |\n| 13. | [How to find the Power of a Number (m^n)?](#power-of-a-number-mn) |\n| 14. | [How to find the Taylor Series?](#taylor-series) |\n| 15. | [How to find the Fibonacci Series (Excessive Recursion and Memoization)?](#fibonacci-series) |\n| 16. | [How to find ⁿCɾ Combination or Selection Formula?](#combination-formula) |\n| 17. | [How to Solve the Tower of Hanoi Problem?](#tower-of-hanoi) |\n| 18. | [How to find the Number of Ways in an n X m Matrix?](#number-of-ways-in-matrix) |\n\n---\n---\n\n## Linked List\n\n| No. | Questions |\n| --- | ----------------------------------------------------------------- |\n| 1.  | [What is a Linked List?](#what-is-a-linked-list) |\n| 2.  | [How Does a Linked List Work?](#how-does-a-linked-list-work) |\n| 3.  | [What is a Self-Referential Structure?](#what-is-a-self-referential-structure) |\n| 4.  | [Understanding Node Structure](#understanding-node-structure) |\n| 5.  | [What are the Common Conditions in a Linked List?](#what-are-the-common-conditions-in-a-linked-list) |\n| 6.  | [How to Create a Linked List](#how-to-create-a-linked-list) |\n| 7.  | [How to Display a Linked List](#how-to-display-a-linked-list) |\n| 8.  | [How to Reverse Display a Linked List](#how-to-reverse-display-a-linked-list) |\n| 9.  | [What is the Time Complexity of Linked List Operations?](#what-is-the-time-complexity-of-linked-list-operations) |\n| 10. | [How to Count Nodes in a Linked List](#how-to-count-nodes-in-a-linked-list) |\n| 11. | [How to Find the Sum of Elements in a Linked List](#how-to-find-the-sum-of-elements-in-a-linked-list) |\n| 12. | [How to Find the Maximum Element in a Linked List](#how-to-find-the-maximum-element-in-a-linked-list) |\n| 13. | [How to Apply Linear Search in a Linked List](#how-to-apply-linear-search-in-a-linked-list) |\n| 14. | [What is Move to Head in a Linked List?](#what-is-move-to-head-in-a-linked-list) |\n| 15. | [What is Move to Transposition?](#what-is-move-to-transposition) |\n| 16. | [How to Insert a Node in a Linked List](#how-to-insert-a-node-in-a-linked-list) |\n| 17. | [How to Delete a Node in a Linked List](#how-to-delete-a-node-in-a-linked-list) |\n| 18. | [How to Check if a List is sorted or not](#how-to-check-if-a-list-is-sorted-or-not) |\n| 19. | [How to Remove Duplicates from Linked List](#how-to-remove-duplicates-from-list) |\n| 20. | [How to Reverse a Linked List](#how-to-reverse-a-linked-list) |\n| 21. | [How to Concatenate Linked Lists](#how-to-concatenate-linked-lists) |\n| 22. | [How to Merge Linked Lists](#how-to-merge-linked-lists) |\n| 23 | [How to Find the Middle of a Linked List](#how-to-find-the-middle-of-a-linked-list) |\n| 24. | [How to Detect and Remove a Loop in a Linked List](#how-to-detect-and-remove-a-loop-in-a-linked-list) |\n\n---\n---\n\n## Circular Linked List\n\n| No. | Questions |\n| --- | ----------------------------------------------------------------- |\n| 1.  | [What is a Circular Linked List?](#what-is-a-circular-linked-list) |\n| 2.  | [What are the conditions for a Circular Linked List?](#conditions-for-a-circular-linked-list) |\n| 3.  | [What are the benefits of a Circular Linked List over a Singly Linked List?](#benefits-of-a-circular-linked-list) |\n| 4.  | [How to create a Circular Linked List?](#creating-a-circular-linked-list) |\n| 5.  | [How to display a Circular Linked List?](#displaying-a-circular-linked-list) |\n| 6.  | [How to insert a node in a Circular Linked List?](#inserting-in-a-circular-linked-list) |\n| 7.  | [How to delete a node from a Circular Linked List?](#deleting-a-node-in-a-circular-linked-list) |\n\n---\n---\n\n## Doubly Linked List\n\n| No. | Questions |\n| --- | ----------------------------------------------------------------- |\n| 1.  | [What is a Doubly Linked List?](#what-is-a-doubly-linked-list) |\n| 2.  | [What are the benefits of a Doubly Linked List over a Singly or Circular Linked List?](#benefits-of-a-doubly-linked-list) |\n| 3.  | [How to create a Doubly Linked List?](#creating-a-doubly-linked-list) |\n| 4.  | [How to display a Doubly Linked List?](#displaying-a-doubly-linked-list) |\n| 5.  | [How to insert a node in a Doubly Linked List?](#inserting-in-a-doubly-linked-list) |\n| 6.  | [How to delete a node from a Doubly Linked List?](#deleting-a-node-in-a-doubly-linked-list) |\n| 7.  | [How to reverse a Doubly Linked List?](#reversing-a-doubly-linked-list) |\n\n---\n---\n\n## Circular Doubly Linked List\n\n| No. | Questions |\n| --- | ----------------------------------------------------------------- |\n| 1.  | [What is a Circular Doubly Linked List?](#what-is-a-circular-doubly-linked-list) |\n| 2.  | [What are the benefits of a Circular Doubly Linked List over Singly, Circular, and Doubly Linked Lists?](#benefits-of-a-circular-doubly-linked-list) |\n| 3.  | [What are the conditions for a Circular Doubly Linked List?](#conditions-for-a-circular-doubly-linked-list) |\n| 4. | [How to create a Circular Doubly Linked List?](#how-to-create-a-circular-doubly-linked-list) |\n| 5.  | [How to display a Circular Doubly Linked List?](#displaying-a-circular-doubly-linked-list) |\n\n---\n\n| No. | Questions |\n| --- | ----------------------------------------------------------------- |\n| 1.  | [Give a Brief Comparison of Linked List Types](#comparison-of-linked-list-types) |\n| 2.  | [Comparison of Linked List with Array](#comparison-of-linked-list-with-array) |\n| 3.  | [How to find the intersection point of two Linked Lists?](#finding-the-intersection-point-of-two-linked-lists) |\n\n---\n---\n\n## Stack\n\n| No. | Questions |\n| --- | ----------------------------------------------------------------- |\n| 1. | [What is Stack?](#what-is-stack) |\n| 2. | [What is ADT with Stack?](#adt-data-representation-and-operations-of-stack) |\n| 3. | [What are the benefits of Stack over Array and Linked List?](#benefits-of-stack-over-array-and-linked-list)|\n| 4. | [How to implement Stack using Array?](#stack-using-array)|\n| 5. | [How to implement Stack using Linked List?](#stack-using-linked-list)|\n| 6. | [How to solve Parenthesis Matching problem using Stack?](#parenthesis-matching)|\n| 7. | [How to check balance with conditions of matching brackets?](#checking-balance-with-condition-of-matching-brackets)|\n| 8. | [How to perform Infix to Postfix Conversion using Stack?](#infix-to-postfix-conversion) |\n\n---\n---\n\n\n## Queue\n\n| No. | Questions |\n| --- | ----------------------------------------------------------------- |\n| 1.  | [What is Queue?](#what-is-queue) |\n| 2.  | [What is ADT in Queue?](#what-is-adt-in-queue) |\n| 3.  | [What are the benefits of Queue over Array, Linked List, and Stack?](#what-are-the-benefits-of-queue-over-array-linked-list-and-stack) |\n| 4.  | [How to implement Queue using Array?](#how-to-implement-queue-using-array) |\n| 5.  | [What are the drawbacks of Queue?](#what-are-the-drawbacks-of-queue) |\n| 6.  | [What is Circular Queue?](#what-is-circular-queue) |\n| 7.  | [How to implement Queue using Linked List?](#how-to-implement-queue-using-linked-list) |\n\n## DEQueue (Double Ended Queue)\n\n| No. | Questions |\n| --- | ----------------------------------------------------------------- |\n| 1. | [What is DEQueue?](#what-is-dequeue) |\n| 2. | [What are the Restrictions in DEQueue?](#restrictions-in-dequeue) |\n\n## Priority Queues\n\n| No. | Questions |\n| --- | ----------------------------------------------------------------- |\n| 1. | [What is Priority Queue?](#what-is-priority-queue) |\n| 2. | [What does it mean by Limited Set of Priorities?](#limited-set-of-priorities) |\n| 3. | [What does it mean by Element Priority? Explain methods.](#element-priority) |\n\n---\n\n| No. | Questions |\n| --- | ----------------------------------------------------------------- |\n| 1.  | [How to Implement Queue using 2 Stacks](#how-to-implement-queue-using-stacks) |\n\n---\n---\n\n## Trees\n\n| No. | Question |\n|----|--------------------------------|\n| 1. | [What is a Tree?](#what-is-a-tree) |\n| 2. | [What are the terminologies in a tree?](#what-are-the-terminologies-in-a-tree) |\n| 2.1. | [What is the Root Node?](#the-root-node) |\n| 2.2. | [What are Edges in a Tree?](#edges-in-a-tree) |\n| 2.3. | [What is a Parent and Child Node?](#parent-and-child-node) |\n| 2.4. | [What are Siblings in a Tree?](#siblings-in-a-tree) |\n| 2.5. | [What is a Subtree?](#subtree) |\n| 2.6. | [What are Descendants in a Tree?](#descendants-in-a-tree) |\n| 2.7. | [What are Ancestors in a Tree?](#ancestors-in-a-tree) |\n| 2.8. | [What is the Degree of a Node?](#degree-of-a-node) |\n| 2.9. | [What is the Degree of a Tree?](#degree-of-a-tree) |\n| 2.10. | [What is a Leaf Node (External Node)?](#leaf-node-external-node) |\n| 2.11. | [What is an Internal Node (Non-Leaf Node)?](#internal-node-non-leaf-node) |\n| 2.12. | [What is Level in a Tree?](#level-in-a-tree) |\n| 2.13. | [What is the Height of a Tree?](#height-of-a-tree) |\n| 2.14. | [What is a Forest in Tree Data Structures?](#forest-in-tree-data-structures) |\n| 2.15. | [What is the Maximum Number of Nodes in a Tree?](#maximum-number-of-nodes-in-a-tree) |\n| 3. | [What is a Binary Tree?](#what-is-binary-tree) |\n| 4. | [How to find Height or Nodes of a Binary Tree if one is given?](#how-to-find-height-or-nodes-of-binary-tree-if-one-is-given) |\n| 5. | [What is a Strict Binary Tree?](#what-is-strict-binary-tree) |\n| 6. | [How to find Height or Nodes of a Strict Binary Tree if one is given?](#how-to-find-height-or-nodes-of-strict-binary-tree-if-one-is-given) |\n| 7. | [What are n-ary trees?](#what-are-n-ary-trees) |\n| 8. | [What are strict n-ary trees?](#what-are-strict-n-ary-trees) |\n| 9. | [How to implement a Binary Tree using an array?](#how-to-implement-binary-tree-using-array) |\n| 10. | [How to implement a Binary Tree using a linked list?](#how-to-implement-binary-tree-using-linked-list) |\n| 11. | [What are the Types of Binary Trees?](#what-are-the-types-of-binary-trees) |\n| 11.1. | [What is a Full Binary Tree?](#what-is-a-full-binary-tree) |\n| 11.2. | [What is a Complete Binary Tree?](#what-is-a-complete-binary-tree) |\n| 12. | [What are the Types/Different Methods of Tree Traversals?](#what-are-the-types-of-tree-traversals) |\n| 12.1. | [What is Preorder Traversal? Explain and provide code for both recursive and iterativees.](#what-is-preorder-traversal) |\n| 12.2. | [What is Inorder Traversal? Explain and provide code for both recursive and iterativees.](#what-is-inorder-traversal) |\n| 12.3. | [What is Postorder Traversal? Explain and provide code for both recursive and iterativees.](#what-is-postorder-traversal) |\n| 12.4. | [What is Level Order Traversal? Explain and provide code for both recursive and iterativees.](#what-is-level-order-traversal) |\n| 13. | [How to implement/create a Binary Tree?](#how-to-implementcreate-binary-tree) |\n| 14. | [How to generate a Tree from Traversal?](#how-to-generate-tree-from-traversal) |\n| 15. | [How to Count Total Nodes, Nodes with Data, Full Nodes, Nodes with One or Two Children, Leaf Nodes, and Nodes with Exactly One Child in a Tree?](how-to-count-nodes-nodes-data-nodes-and-other) |\n\n---\n---\n\n## Binary Search Tree (BST)\n\n| No. | Question |\n|----|------------------------------------------------|\n| 1.  | [What is Binary Search Tree (BST)?](#what-is-binary-search-tree-bst) |\n| 2.  | [What are the Key Properties of a Binary Search Tree (BST)?](#what-are-the-key-properties-of-a-binary-search-tree) |\n| 3.  | [How to Search in a BST? Explain and provide code for both recursive and iterative approaches.](#how-to-search-in-bst-explain-and-provide-code-for-both-recursive-and-iterative-approaches) |\n| 4.  | [How to Insert in a BST? Explain and provide code for both recursive and iterative approaches.](#how-to-insert-in-bst-explain-and-provide-code-for-both-recursive-and-iterative-approaches) |\n| 5.  | [How to Delete a Node in a BST? Explain and provide code for both recursive and iterative approaches. Also, explain what a Predecessor and Successor are.](#how-to-delete-in-bst-explain-and-provide-code-for-both-recursive-and-iterative-approaches) |\n| 6. | [How to Construct a BST from a Given Preorder Traversal?](#how-to-construct-a-bst-from-a-given-preorder-traversal) |\n| 7.  | [What are the Drawbacks of BST and How Can They Be Solved?](#what-are-the-drawbacks-of-bst-and-how-can-they-be-solved) |\n\n---\n---\n\n## AVL Trees\n\n| No. | Question |\n|----|------------------------------------------------|\n| 1.  | [What is AVL Tree?](#what-is-avl-tree) |\n| 2.  | [How to Balance AVL Trees?](#how-to-balance-avl-trees) |\n| 3.  | [What are the Types of Rotations Used for Balancing AVL Trees?](#what-are-the-types-of-rotations-used-for-balancing-avl-trees) |\n| 3.1 | [LL (Left-Left) Rotation](#ll-left-left-rotation) |\n| 3.2 | [RR (Right-Right) Rotation](#rr-right-right-rotation) |\n| 3.3 | [LR (Left-Right) Rotation](#lr-left-right-rotation) |\n| 3.4 | [RL (Right-Left) Rotation](#rl-right-left-rotation) |\n| 4.  | [How to Perform Deletion in AVL Tree?](#how-to-perform-deletion-in-avl-tree) |\n| 5.  | [How to Find Height or Nodes of an AVL Tree?](#how-to-find-height-or-nodes-of-an-avl-tree) |\n| 6.  | [Comparison of AVL Trees and BSTs: Benefits Over BSTs](#comparison-of-avl-trees-and-bsts-benefits-over-bsts) |\n| 7.  | [What are the Applications of AVL Trees: When Are They Preferred?](#applications-of-avl-trees-when-are-they-preferred) |\n\n---\n---\n\n## Binary Heap\n\n| No. | Question |\n|----|------------------------------------------------|\n| 1.  | [What is Binary Heap? What are its Characteristics?](#what-is-binary-heap-what-are-its-characteristics) |\n| 2.  | [Which is the Preferred Way to Implement Binary Heap?](#which-is-the-preferred-way-to-implement-binary-heap) |\n| 3.  | [How to Implement Binary Heap Using an Array?](#how-to-implement-binary-heap-using-an-array) |\n| 4.  | [How to Perform Operations on Binary Heap?](#how-to-perform-operations-on-binary-heap) |\n| 5.  | [Explain the Concept of Heapify Process](#explain-the-concept-of-heapify-process) |\n| 6.  | [What is Binary Heap as a Priority Queue?](#what-is-binary-heap-as-a-priority-queue) |\n\n---\n---\n\n## Sorting Techniques\n\n| No. | Question |\n|----|------------------------------------------------------------|\n| 1.  | [What are Sorting Techniques?](#what-are-sorting-techniques) |\n| 2.  | [What are the Criteria for Analyzing a Sorting Algorithm?](#what-are-the-criteria-for-analyzing-a-sorting-algorithm) |\n| 3.  | [What are the Different Types of Sorting Algorithms? (Comparison-Based and Index-Based)](#what-are-the-different-types-of-sorting-algorithms) |\n| 4.  | [What is Bubble Sort? Explain with an Example.](#what-is-bubble-sort-explain-with-an-example) |\n| 5.  | [What is Insertion Sort? Explain with an Example.](#what-is-insertion-sort-explain-with-an-example) |\n| 6.  | [What is the Difference between Bubble Sort and Insertion Sort](#bubble-sort-vs-insertion-sort-key-differences) |\n| 7.  | [What is Selection Sort? Explain with an Example.](#what-is-selection-sort-explain-with-an-example) |\n| 8.  | [What is Quick Sort? Explain with an Example.](#what-is-quick-sort-explain-with-an-example) |\n| 9.  | [What is the Difference between Selection Sort and Quick Sort](#selection-sort-vs-quick-sort-key-differences) |\n| 10. | [What is Merge Sort? Explain and Provide Code for Both Recursive and Iterativees.](#what-is-merge-sort-explain-and-provide-code) |\n| 11. | [What is Counting Sort? Explain with an Example.](#what-is-counting-sort-explain-with-an-example) |\n| 12. | [What is Bucket/Bin Sort? Explain with an Example.](#what-is-bucket-bin-sort-explain-with-an-example) |\n| 13. | [What is Radix Sort? Explain with an Example.](#what-is-radix-sort-explain-with-an-example) |\n| 14. | [What is Shell Sort? Explain with an Example.](#what-is-shell-sort-explain-with-an-example) |\n\n---\n---\n\n## Hashing Techniques\n\n| No. | Question |\n|----|--------------------------------------------------------------|\n| 1.  | [What is Hashing?](#what-is-hashing) |\n| 2.  | [Why is Hashing Useful for Searching?](#why-is-hashing-useful-for-searching) |\n| 3.  | [How Does Hashing Work?](#how-does-hashing-work) |\n| 4.  | [What are the Different Types of Mappings in Hashing?](#types-of-mappings-in-hashing) |\n| 5.  | [What is a Hash Collision?](#what-is-a-hash-collision) |\n| 6.  | [What are the Methods for Resolving Hash Collisions?](#methods-for-resolving-hash-collisions) |\n| 7.  | [What is Chaining in Hashing? (With Analysis)](#what-is-chaining-in-hashing) |\n| 8.  | [What is Linear Probing? (With Analysis)](#what-is-linear-probing) |\n| 9.  | [What is Quadratic Probing? (With Analysis)](#what-is-quadratic-probing) |\n| 10. | [What is Double Hashing?](#what-is-double-hashing) |\n| 11. | [Comparison: Linear Probing vs. Quadratic Probing vs. Double Hashing](#comparison-linear-probing-vs-quadratic-probing-vs-double-hashing) |\n| 12. | [What are Hash Functions?](#what-are-hash-functions) |\n| 13. | [What are the Different Types of Hash Functions?](#types-of-hash-functions) |\n\n---\n---\n\n## STL (Standard Template Library)\n\n| No. | Topic |\n|----|--------------------------------------------------------------|\n| 1.  | [What is STL?](#what-is-stl) |\n| 2.  | [Why Use STL?](#why-use-stl) |\n| 3.  | [When to Use Which STL Container?](#when-to-use-which-stl-container) |\n| 4.  | [Main Components of STL](#main-components-of-stl) |\n| 5.  | [Pairs](#pairs-in-stl) |\n| 6.  | [Vectors](#vectors-in-stl) |\n| 7.  | [Lists](#lists-in-stl) |\n| 8.  | [Deques](#deques-in-stl) |\n| 9.  | [Stack (LIFO)](#stack-lifo-in-stl) |\n| 10. | [Queue (FIFO)](#queue-fifo-in-stl) |\n| 11. | [Priority Queue](#priority-queue) |\n| 12. | [Set](#set) |\n| 13. | [Multiset](#multiset) |\n| 14. | [Unordered Set](#unordered-set) |\n| 15. | [Map](#map)|\n| 16. | [Multimap](#multimap) |\n| 17. | [Unordered Map](#unordered-map) |\n| 18. | [Algorithms](#algorithms) |\n\n---\n---\n\n## Introduction to DSA\n\n### What is Data Structure? 📂\n\n- A **Data Structure** is a way of organizing and storing data in memory during program execution.\n- It allows **efficient storage, retrieval, and manipulation** of data.\n- Data structures use **algorithms** to structure data efficiently in memory.\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### How is Data Organized in Memory?\n\nThe way data is stored in main memory for efficient access is called a **Data Structure**.\nMemory is divided into three main sections:\n\n1. **Code Section** 🖥️\n   - Contains the program's executable instructions.\n   - Execution starts from this section.\n\n2. **Stack Section** 📌\n   - Stores function calls and local variables.\n   - Uses **Last In, First Out (LIFO)** order.\n   - Memory is **statically allocated** and automatically managed.\n\n3. **Heap Section** 📂\n   - Stores dynamically allocated memory (e.g., `malloc()` in C or `new` in C++/Java).\n   - Accessed via **pointers**.\n   - Memory needs to be **manually managed** (deallocation required).\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### Stack vs Heap Memory\n\n| Feature   🔥 | Stack Memory 📌 | Heap Memory 📂 |\n|-------------|---------------|---------------|\n| Allocation  | Static        | Dynamic       |\n| Access Speed | Faster        | Slower       |\n| Size        | Limited       | Large        |\n| Lifetime    | Auto-managed  | Manually managed (deallocation required) |\n| Usage      | Function calls, local variables | Dynamic objects, large data structures |\n\n- The **stack** is efficient but limited in size.\n- The **heap** is flexible but requires proper memory management.\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n#### \u003ca id=\"types-of-data-structures\"\u003e\u003c/a\u003e🤷‍♂️ Types of Data Structures\n\n#### **Physical Data Structures**\n- Define how data is stored in memory.\n  - **Array**: Fixed size, used when the max size is known.\n  - **Linked List**: Dynamic, stored in heap, suitable when size is unknown.\n\n#### **Logical Data Structures**\n- Define data operations like searching \u0026 sorting.\n  - **Stack**: Last In, First Out (LIFO)\n  - **Queue**: First In, First Out (FIFO)\n  - **Tree \u0026 Graph**: Non-linear structures\n  - **Hash Table**: Key-value pairs for quick lookup\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### \u003ca id=\"time-and-space-complexity\"\u003e\u003c/a\u003eTime and Space Complexity\n\n#### **⏳ Time Complexity**\n\n- Measures algorithm efficiency as input size increases.\n- Ignoring constants: `O(n + 1) → O(n)`.\n- Common complexities:\n  - `O(1)`: Constant time (random access in an array).\n  - `O(log n)`: Logarithmic time (Binary Search).\n  - `O(n)`: Linear time (Loop through an array).\n  - `O(n log n)`: Quasi-linear (Merge Sort, Quick Sort).\n  - `O(n²)`: Quadratic time (Bubble Sort, Insertion Sort).\n\n#### **🗄️ Space Complexity**\n\n- Determines memory usage based on input size.\n- Includes auxiliary space (extra space required apart from input data).\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n#### ⏱️ Quick Guide to Measuring Time Complexity\n\n#### 1. Loop-Based Patterns\n\n| Pattern | Code Example | Time Complexity |\n|---------|-------------|----------------|\n| Single Loop | `for (int i = 0; i \u003c n; i++)` | O(n) |\n| Nested Loops | `for (int i = 0; i \u003c n; i++)` `for (int j = 0; j \u003c n; j++)` | O(n²) |\n| Triple Nested Loops | `for (int i = 0; i \u003c n; i++)` `for (int j = 0; j \u003c n; j++)` `for (int k = 0; k \u003c n; k++)` | O(n³) |\n| Loop with Increment (`i *= 2`) | `for (int i = 1; i \u003c n; i *= 2)` | O(log n) |\n| Loop with Decrement (`i /= 2`) | `for (int i = n; i \u003e 0; i /= 2)` | O(log n) |\n\n#### 2. Recursive Patterns\n\n| Pattern | Recurrence Relation | Time Complexity |\n|---------|---------------------|----------------|\n| Linear Recursion | `T(n) = T(n-1) + O(1)` | O(n) |\n| Binary Recursion | `T(n) = 2T(n/2) + O(1)` | O(n) |\n| Divide \u0026 Conquer (Merge Sort, Quick Sort Worst Case) | `T(n) = 2T(n/2) + O(n)` | O(n log n) |\n| Exponential Recursion (Fibonacci, Brute Force DFS) | `T(n) = T(n-1) + T(n-2)` | O(2ⁿ) |\n\n#### 3. Divide and Conquer Patterns\n\n| Algorithm | Recurrence | Complexity |\n|-----------|------------|------------|\n| Binary Search | `T(n) = T(n/2) + O(1)` | O(log n) |\n| Merge Sort | `T(n) = 2T(n/2) + O(n)` | O(n log n) |\n| Quick Sort (Best \u0026 Avg) | `T(n) = T(n/2) + O(n)` | O(n log n) |\n| Quick Sort (Worst Case - sorted array) | `T(n) = T(n-1) + O(n)` | O(n²) |\n\n#### 4. Dynamic Programming Patterns\n\n| Pattern | Example | Time Complexity |\n|---------|---------|----------------|\n| Memoization (Top-Down Recursion with Cache) | Fibonacci DP | O(n) |\n| Bottom-Up Iterative DP | Knapsack, LIS | O(n²) or O(n³) |\n| Matrix Chain Multiplication | `T(n) = O(n³)` | O(n³) |\n\n#### 5. Graph Algorithms\n\n| Algorithm | Complexity |\n|-----------|------------|\n| BFS / DFS (Adjacency List) | O(V + E) |\n| Dijkstra (Min Heap) | O((V + E) log V) |\n| Bellman-Ford | O(VE) |\n| Floyd Warshall (All-Pairs Shortest Path) | O(V³) |\n| Prim’s / Kruskal’s MST | O(E log V) |\n\n#### 6. Sorting Algorithms\n\n| Algorithm | Best Case | Worst Case |\n|-----------|------------|------------|\n| Bubble Sort / Insertion Sort | O(n) | O(n²) |\n| Merge Sort | O(n log n) | O(n log n) |\n| Quick Sort | O(n log n) | O(n²) |\n| Heap Sort | O(n log n) | O(n log n) |\n\n#### 7. Logarithmic and Amortized Complexities\n\n| Pattern | Example | Complexity |\n|---------|---------|------------|\n| Binary Search | Search in sorted array | O(log n) |\n| Heap Operations (Insert/Delete) | Priority Queue, Dijkstra | O(log n) |\n| Balanced BST (Insertion, Deletion, Search) | AVL, Red-Black Tree | O(log n) |\n| Union-Find (Path Compression \u0026 Rank) | DSU operations | O(α(n)) (inverse Ackermann) |\n\n#### 8. Special Cases\n\n| Case | Example |\n|------|---------|\n| Iterating All Subsets | O(2ⁿ) |\n| Iterating All Permutations | O(n!) |\n| Brute Force Checking All Pairs | O(n²) |\n\n---\n\n### 💾 Quick Guide to Calculating Space Complexity\n\n#### 1. What is Space Complexity?\nSpace Complexity is the total memory required by a program to execute. It includes:\n1. Fixed Part – Independent of input size (e.g., code, static/global variables, constants).\n2. Variable Part – Depends on input size (e.g., dynamic memory allocation, function call stack, recursion depth).\n\n#### 2. Components of Space Complexity\n##### a) Fixed Memory (O(1))\n- Code Space: Memory occupied by compiled instructions.\n- Constant Space: Fixed-size variables, constants.\n- Global \u0026 Static Variables: Memory allocated at program startup, remains till termination.\n\n##### b) Variable Memory (Depends on Input)\n- Stack Space: Used for function calls (parameters, return addresses, local variables).\n- Heap Space: Memory dynamically allocated using `new` in Java/C++, `malloc()` in C.\n- Data Structures: Arrays, lists, trees, hash tables, etc.\n\n#### 3. Steps to Calculate Space Complexity\n##### Step 1: Analyze Fixed Space\n```cpp\nint a = 10, b = 20; // Fixed space O(1)\n```\n##### Step 2: Analyze Variable Space\n```cpp\nint[] arr = new int[n]; // Takes O(n) space\n```\n##### Step 3: Analyze Function Calls \u0026 Stack Usage\n```cpp\nvoid recursive(int n) {\n    if (n == 0) return;\n    recursive(n - 1);\n} // O(n) stack space\n```\n##### Step 4: Consider Auxiliary Space\n```cpp\nint[] newArray = new int[n]; // O(n) auxiliary space\n```\n\n#### 4. Space Complexity Analysis for Common Data Structures\n\n| Data Structure | Space Complexity |\n|---------------|-----------------|\n| Array (1D) | O(n) |\n| 2D Array | O(n²) |\n| Linked List | O(n) |\n| HashMap | O(n) |\n| Tree (Balanced) | O(n) |\n| Graph (Adjacency List) | O(V + E) |\n| Stack (n elements) | O(n) |\n| Queue (n elements) | O(n) |\n\n#### 5. Space Complexity of Common Algorithms\n\n##### Iterative Algorithm (O(1))\n```cpp\nvoid printArray(int arr[], int n) {\n    for (int i = 0; i \u003c n; i++) {\n        cout \u003c\u003c arr[i] \u003c\u003c \" \";\n    }\n} // O(1) space\n```\n\n##### Recursive Algorithm (O(n))\n```cpp\nint factorial(int n) {\n    if (n == 0) return 1;\n    return n * factorial(n - 1);\n} // O(n) stack space\n```\n\n##### Sorting Algorithms\n\n| Algorithm | Auxiliary Space |\n|-----------|----------------|\n| Bubble Sort | O(1) |\n| Merge Sort | O(n) |\n| Quick Sort (in-place) | O(log n) |\n| Heap Sort | O(1) |\n\n#### 6. Best Practices for Optimizing Space Complexity\n- Use In-Place Algorithms\n- Use Iteration Instead of Recursion\n- Choose Space-Efficient Data Structures\n- Free Memory When Not Needed\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n---\n---\n\n## Array Representations\n\n### What is an Array?\n- Array is like a container that is use to store some kind of data or collection of elements.\n- It is a linear data structure. And have contiguous memory locations.\n- It allows easy access to elements using an index.\n- Example:\n  ```cpp\n  int arr[5] = {1, 2, 3, 4, 5};\n  ```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### What are Dynamic Arrays?\n- A **dynamic array** can change its size during runtime.\n- It is implemented using pointers and memory allocation functions like `new` in C++.\n- Can grow or shrink during runtime using `new` and `delete`.\n- ```cpp\n  int *arr = new int[10];\n  ```\n- ```cpp\n  #include\u003ciostream\u003e\n  using namespace std;\n\n  int main(){\n      int *arr = new int[5];\n      for(int i = 0; i \u003c 5; i++){\n          cout \u003c\u003c \"Enter \" \u003c\u003c i + 1 \u003c\u003c \" element: \";\n          cin \u003e\u003e arr[i];\n      }\n      delete[] arr;\n  }\n  ```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### What are Static Arrays?\n- A **static array** has a fixed size determined at compile time.\n- Fixed-size memory allocation.\n- Cannot grow or shrink dynamically.\n-\n  ```cpp\n  int arr[10];\n  ```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n```cpp\n#include\u003ciostream\u003e\nusing namespace std;\n\nint main(){\n    int *a = new int[5];\n\n    for(int i = 0; i \u003c 5; i++){\n        cout \u003c\u003c \"Enter \" \u003c\u003c i + 1 \u003c\u003c \" element: \";\n        cin \u003e\u003e a[i];\n    }\n\n    char i;\n    cout \u003c\u003c \"Do you want to increase the size of array? (Y/N): \";\n    cin \u003e\u003e i;\n\n    if(i == 'Y'){\n        int num;\n        cout \u003c\u003c \"\\nEnter number of elements you want to add: \";\n        cin \u003e\u003e num;\n\n        int *b = new int[5 + num];\n\n        for(int i = 0; i \u003c 5; i++){\n            b[i] = a[i];\n        }\n\n        for(int i = 5; i \u003c 5 + num; i++){\n            cout \u003c\u003c \"Enter \" \u003c\u003c i + 1 \u003c\u003c \" element: \";\n            cin \u003e\u003e b[i];\n        }\n\n        delete[] a;\n        a = b;\n        b = nullptr;\n\n        for(int i = 0; i \u003c 5 + num; i++){\n            cout \u003c\u003c a[i] \u003c\u003c \" \";\n        }\n    }else{\n        for(int i = 0; i \u003c 5; i++){\n            cout \u003c\u003c a[i] \u003c\u003c \" \";\n        }\n    }\n\n    delete[] a;\n}\n```\n\n---\n\n### Advantages and Disadvantages of Arrays\n\n| **Advantages**                                     | **Disadvantages**                                      |\n|--------------------------------------------------|------------------------------------------------------|\n| Fast access to elements using an index.         | Fixed size (static arrays) cannot be resized.       |\n| Efficient memory usage for storing similar data. | Insertion and deletion are costly due to shifting.  |\n| Easier to traverse using loops.                  | - |\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### What is a 2D Array?\n\n- A **2D array** represents data in a tabular format with rows and columns.\n- Commonly used to implement matrices.\n- Accessed using two indices (one for row and one for column).\n```cpp\nint matrix[3][3] = {\n      {1, 2, 3},\n      {4, 5, 6},\n      {7, 8, 9}\n  };\n  ```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### What defines the Dimensionality of an Array?\n- The number of indices needed to access an element defines the **dimensionality** of an array.\n- Example:\n  - **1D Array:** `arr[5]`\n  - **2D Array:** `arr[3][3]`\n  - **3D Array:** `arr[3][3][3]`\n\n**[⬆ Back to Top](#table-of-contents)**\n\n\n---\n\n### Methods/Ways of Declaring 2D Arrays\n\n#### 1. Normal Declaration\n\n- Memory will be created like a single dimension array , but compiler will allow us to access that array as a 2D arrays with rows and columns.\n```cpp\nint A[3][4] = {\n    {1,2,3,4},\n    {2,4,6,8},\n    {3,5,7,9}\n};\n```\n\n#### 2. Array of Pointers\n\n- The pointer will be created inside heap memory and through that we can access , initialise and declare all the elements inside the array. This is array of arrays.\n```cpp\nint *A[3];\nA[0] = new int[4];\nA[1] = new int[4];\nA[2] = new int[4];\n```\n```cpp\nint row, col;\ncout \u003c\u003c \"Number of rows, col: \";\ncin \u003e\u003e row \u003e\u003e col;\nint *A[row];\nfor(int i = 0; i \u003c row; i++){\n    A[i] = new int[col];\n}\n\nfor(int i = 0; i \u003c row; i++){\n    for(int j = 0; j \u003c col; j++){\n        cout \u003c\u003c \"Enter A[\" \u003c\u003c i \u003c\u003c \"][\" \u003c\u003c j \u003c\u003c \"] element: \";\n        cin \u003e\u003e A[i][j];\n    }\n}\n\nfor(int i = 0; i \u003c row; i++){\n    for(int j = 0; j \u003c col; j++){\n        cout \u003c\u003c A[i][j] \u003c\u003c \" \";\n    }\n    cout \u003c\u003c endl;\n}\n\nfor(int i = 0; i \u003c row; i++){\n    delete[] A[i];\n}\n\ndelete[] A;\n```\n\n#### 3. Double Pointer Method\n\n- Almost everything is inside the heap pointer.\n- The pointer acts like a variable; there is no `new` operator for it, so it is created inside the stack.\n\n```cpp\nint **A;\nA = new int*[3];\nfor(int i = 0; i \u003c 3; i++){\n    A[i] = new int[4];\n}\n```\n```cpp\nint **A;\n    A = new int*[3]; // Allocating memory for 3 rows\n    for(int i = 0; i \u003c 3; i++){\n        A[i] = new int[4]; // Allocating memory for 4 columns in each row\n    }\n\n    // Example usage: Assigning values\n    for(int i = 0; i \u003c 3; i++){\n        for(int j = 0; j \u003c 4; j++){\n            A[i][j] = (i + 1) * (j + 1); // Sample values\n        }\n    }\n\n    // Displaying the 2D array\n    cout \u003c\u003c \"2D Array Elements:\\n\";\n    for(int i = 0; i \u003c 3; i++){\n        for(int j = 0; j \u003c 4; j++){\n            cout \u003c\u003c A[i][j] \u003c\u003c \" \";\n        }\n        cout \u003c\u003c endl;\n    }\n\n    // Freeing allocated memory\n    for(int i = 0; i \u003c 3; i++){\n        delete[] A[i]; // Deleting columns\n    }\n    delete[] A; // Deleting row pointers\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n---\n---\n\n## Array as ADT (Abstract Data Type)\n\n### What is Array ADT?\n\nAn **Array ADT (Abstract Data Type)** consists of:\n1. **Data Representation** (handled by the compiler)\n2. **Operations on Data** (defined by the program)\n\n#### **Key Components of Array ADT:**\n- **Data:**\n  - **Array space** → Memory allocated for the array.\n  - **Size** → Total allocated memory.\n  - **Length** → Number of elements currently stored.\n\n- **Operations:**\n  - `Display()` → Show all elements.\n  - `Add(x)` / `Append(x)` → Add an element at the end.\n  - `Insert(index, x)` → Insert an element at a specific position.\n  - `Delete(index)` → Remove an element.\n  - `Search(x)` → Find an element.\n  - `Get(index)` → Retrieve an element at a specific position.\n  - `Set(index, x)` → Update an element.\n  - `Max / Min` → Find the maximum or minimum element.\n  - `Reverse` → Reverse the array.\n  - `Shift / Rotate` → Move elements left or right.\n\n- `size = 10`, but only `length = 5` elements are used in an array.\n- This means 5 slots are empty but allocated in memory.\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### How to Add / Append?\n\nAdding or **appending** means inserting an element at the **end** of an array.\n\n- The new element is stored at the next available index.\n- The **time complexity** is **O(1)** (constant time) since we are adding at the end.\n\n```cpp\narr[length] = x;  // Insert element at the next index\nlength++;         // Increase the length of the array\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n\n---\n\n### How to Insert?\n\nInsertion means adding an element at a **specific index** in the array.\n\n#### Time Complexity:\n- **Best case (O(1))** → When inserting at the **end**.\n- **Worst case (O(n))** → When inserting at the **beginning** (as elements need to be shifted).\n\n```cpp\n#include \u003ciostream\u003e\nusing namespace std;\n\nclass Arr {\n    private:\n        int *A;\n        int length;\n        int size;\n\n    public:\n        Arr(int size) {\n            this-\u003esize = size;\n            A = new int[size];\n            length = 0;\n        }\n\n        void insert(int num) {\n            if (length \u003c size) {\n                A[length] = num;\n                length++;\n            } else {\n                cout \u003c\u003c \"Array is full!\" \u003c\u003c endl;\n            }\n        }\n\n        void add(int index, int num) {\n            if (index \u003c 0 || index \u003e length) {\n                cout \u003c\u003c \"Invalid index!\" \u003c\u003c endl;\n                return;\n            }\n            if (length == size) {\n                cout \u003c\u003c \"Array is full!\" \u003c\u003c endl;\n                return;\n            }\n            for (int i = length; i \u003e index; i--) {\n                A[i] = A[i - 1];\n            }\n            A[index] = num;\n            length++;\n        }\n\n        void display() {\n            for (int i = 0; i \u003c length; i++) {\n                cout \u003c\u003c A[i] \u003c\u003c \" \";\n            }\n            cout \u003c\u003c endl;\n        }\n\n        ~Arr() {\n            delete[] A;\n            cout \u003c\u003c \"Array destroyed\" \u003c\u003c endl;\n        }\n};\n\nint main() {\n    Arr ar(5);\n    ar.insert(1);\n    ar.insert(2);\n    ar.insert(3);\n    ar.insert(5);\n    ar.add(3, 4);\n    ar.display();\n}\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### How to Delete?\n\n**Deletion** means removing an element from a **specific index** in the array.\n\n#### Time Complexity:\n- **O(n)** → Because elements must be shifted after deletion.\n\n```cpp\nvoid del(int index) {\n    if (index \u003e= 0 \u0026\u0026 index \u003c length) {\n        for (int i = index; i \u003c length - 1; i++) {\n            A[i] = A[i + 1];\n        }\n        length--;\n    }\n}\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### How to Search?\n\nSearching involves finding an element in an array. The two main searching techniques are:\n1. **Linear Search** → Works on both sorted and unsorted arrays.\n2. **Binary Search** → Works only on sorted arrays for faster searching.\n\n**[⬆ Back to Top](#table-of-contents)**\n\n\n---\n\n### What is Linear Search?\n- Linear search is a simple searching algorithm where we traverse the array element by element until we find the key.\n- If we find the element in the array, we return its index; otherwise, we return `-1` to indicate it is not present.\n- The value we are searching for is called the **key**.\n\n#### Time Complexity\n- **Best case time complexity:** `O(1)` (when the key is found at the first position).\n- **Worst case time complexity:** `O(n)` (when the key is at the last position or not present at all).\n\n```cpp\n#include \u003ciostream\u003e\nusing namespace std;\n\nint search(int arr[], int size, int key) {\n    for(int i = 0; i \u003c size; i++) {\n        if(arr[i] == key) {\n            return i; // Return index if found\n        }\n    }\n    return -1; // Return -1 if not found\n}\n\nint main() {\n    int arr[] = {10, 20, 30, 40, 50};\n    int size = sizeof(arr) / sizeof(arr[0]);\n    int key = 30;\n\n    int result = search(arr, size, key);\n    if (result != -1)\n        cout \u003c\u003c \"Element found at index: \" \u003c\u003c result \u003c\u003c endl;\n    else\n        cout \u003c\u003c \"Element not found\" \u003c\u003c endl;\n\n    return 0;\n}\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### How to Improve Linear Search (Move to Head / Move to Front)?\n\n#### Optimization Techniques:\n##### 1. **Transposition:**\nMove the recently searched element one step forward for faster future access.\n#### 2. **Move to Front (Move to Head):**\nMove the frequently searched element to the beginning of the array.\n\n\n##### **1. Transposition:**\nIn this technique, when we find the element, we swap it with the previous element. This ensures that frequently accessed elements move closer to the start over time.\n\n```cpp\n#include \u003ciostream\u003e\nusing namespace std;\n\nclass Arr {\n    public:\n        int arr[10] = {1, 3, 5, 7, 9, 10, 8, 6, 4, 2};\n\n        int search(int key) {\n            for (int i = 0; i \u003c 10; i++) {\n                if (arr[i] == key) {\n                    if (i != 0) {\n                        swap(\u0026arr[i], \u0026arr[i - 1]);\n                        return i - 1;\n                    }\n                    return i;\n                }\n            }\n            return -1;\n        }\n\n        void swap(int *arr1, int *arr2) {\n            int temp = *arr2;\n            *arr2 = *arr1;\n            *arr1 = temp;\n        }\n};\n\nint main() {\n    Arr arr1;\n    cout \u003c\u003c \"Element found at index: \" \u003c\u003c arr1.search(4) \u003c\u003c endl;\n}\n```\n\n##### **2. Move to Front (Move to Head)**\n\nIn this method, whenever an element is found, we swap it with the first element.\nThis ensures that the most frequently searched elements stay at the beginning.\n\n```cpp\n#include \u003ciostream\u003e\nusing namespace std;\n\nclass Arr {\n    public:\n        int arr[10] = {1, 3, 5, 7, 9, 10, 8, 6, 4, 2};\n\n        int search(int key) {\n            for (int i = 0; i \u003c 10; i++) {\n                if (arr[i] == key) {\n                    if (i != 0) {\n                        swap(\u0026arr[i], \u0026arr[0]);\n                        return 0;\n                    }\n                    return i;\n                }\n            }\n            return -1;\n        }\n\n        void swap(int *arr1, int *arr2) {\n            int temp = *arr2;\n            *arr2 = *arr1;\n            *arr1 = temp;\n        }\n};\n\nint main() {\n    Arr arr1;\n    cout \u003c\u003c \"Element found at index: \" \u003c\u003c arr1.search(2) \u003c\u003c endl;\n}\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### What is Binary Search?\n\n- Works only on **sorted** arrays.\n- Always searches for the **middle element** and splits the array into two halves.\n- **Time Complexity:** `O(log n)`\n\n#### **Process:**\n1. If `key == middle element` → ✅ **Found**.\n2. If `key \u003c middle element` → 🔍 Search in **left half**.\n3. If `key \u003e middle element` → 🔍 Search in **right half**.\n\n\n```cpp\n// Iterative\n#include \u003ciostream\u003e\nusing namespace std;\n\nclass Arr {\n    public:\n        int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n\n        int search(int key) {\n            int l = 0, h = 9;\n            int mid;\n            while (l \u003c= h) {\n                mid = (l + h) / 2;\n                if (key == arr[mid])\n                    return mid;\n                else if (key \u003c arr[mid])\n                    h = mid - 1;\n                else\n                    l = mid + 1;\n            }\n            return -1;\n        }\n};\n\nint main() {\n    Arr arr1;\n    cout \u003c\u003c \"Element found at index: \" \u003c\u003c arr1.search(11) \u003c\u003c endl;\n}\n```\n\n```cpp\n// Recursive\n#include \u003ciostream\u003e\nusing namespace std;\n\nclass Arr {\n    public:\n        int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n\n        int search(int key, int l, int h) {\n            if (l \u003c= h) {\n                int mid = (l + h) / 2;\n                if (key == arr[mid])\n                    return mid;\n                else if (key \u003c arr[mid])\n                    return search(key, l, mid - 1);\n                else\n                    return search(key, mid + 1, h);\n            }\n            return -1;\n        }\n};\n\nint main() {\n    Arr arr1;\n    cout \u003c\u003c \"Element found at index: \" \u003c\u003c arr1.search(10, 0, 9) \u003c\u003c endl;\n}\n```\n\n#### **Analysis of Binary Search**\n\n##### Time Complexity: `O(log n)`\n\n- The complexity is determined by the number of comparisons from tracing the **binary tree**.\n\n\n##### For Successful Search:\n- **Best case:** `O(1)`\n- **Worst case:** `O(log n)`\n\n##### For Unsuccessful Search:\n- Always `O(log n)`, whether using **recursion** or **iteration**.\n\n---\n\n### Difference Between Linear and Binary Search:\n\n| **Search Type**     | **Best Case** | **Worst Case** | **Works on Sorted Array?** |\n|---------------------|--------------|---------------|--------------------------|\n| **Linear Search**   | `O(1)`       | `O(n)`        | Yes (But Complexity is High)                     |\n| **Binary Search**   | `O(1)`       | `O(log n)`    | Yes                    |\n\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### How to Get, Set, Find Min - Max?\n\n#### 1. Get(index)\nRetrieves the element at the specified index.\n\n```cpp\nint get(int index) {\n    if (index \u003e= 0 \u0026\u0026 index \u003c 10) // Assuming array size is 10\n        return arr[index];\n    else\n        return -1; // Error value for invalid index\n}\n```\n\n#### 2. Set(index, value)\nModifies the element at the specified index.\n\n```cpp\nvoid set(int index, int value) {\n    if (index \u003e= 0 \u0026\u0026 index \u003c 10) // Assuming array size is 10\n        arr[index] = value;\n}\n```\n\n#### 3. Min()\nFinds the minimum value in the array.\n\n**Time Complexity:** `O(n)`\n\n```cpp\nint getMin(){\n    int min;\n    for(int i = 0; i \u003c 9; i++)\n        if(arr[i] \u003e arr[i + 1])\n            min = arr[i];\n    return min;\n}\n```\n\n#### 4. Max()\nFinds the maximum value in the array.\n\n**Time Complexity:** `O(n)`\n\n```cpp\nint getMax(){\n    int max = arr[0];\n    for(int i = 1; i \u003c 9; i++)\n        if(arr[i] \u003e max)\n            max = arr[i];\n    return max;\n}\n```\n\n#### 5. Sum() + Average()\nCalculates the sum and average of array elements.\n\n**Time Complexity:** `O(n)`\n\n```cpp\n// Iterative\nint getAverage(){\n    int sum = 0;\n    for(int i = 0; i \u003c 10; i++)\n        sum += arr[i];\n    return (sum / 10);\n}\n```\n```cpp\n// Recursive\nint getAverage(int arr[], int num){\n    if(num \u003c 0){\n        return 0;\n    } else {\n        return getAverage(arr, num - 1) + arr[num];\n    }\n}\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### How to Reverse and Shift an Array?\n\nThere are two common methods to reverse an array:\n\n#### 1️. Auxiliary Array Method\n- Create a temporary array.\n- Copy elements in reverse order.\n- Copy back to the original array.\n- **Time Complexity:** `O(2n)`\n\n```cpp\nclass Arr {\n  public:\n    int arr1[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n\n    void reverse() {\n        int arr2[10];\n\n        for(int i = 9, j = 0; i \u003e= 0; i--, j++)\n            arr2[j] = arr1[i];\n\n        for(int i = 0; i \u003c 10; i++)\n            arr1[i] = arr2[i];\n\n        for(int i = 0; i \u003c 10; i++)\n            cout \u003c\u003c arr1[i] \u003c\u003c \" \";\n    }\n};\n\nint main() {\n    Arr arr;\n    arr.reverse();\n}\n```\n\n#### 2. In-Place Swap Method\nSwap elements from the start and end of the array.\n\n- **Time Complexity:** `O(n)`\n\n```cpp\n#include \u003ciostream\u003e\nusing namespace std;\n\nclass Arr {\n  public:\n    int arr1[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n\n    void reverse() {\n        for(int i = 0, j = 9; i \u003c j; i++, j--) {\n            int temp = arr1[j];\n            arr1[j] = arr1[i];\n            arr1[i] = temp;\n        }\n\n        for(int i = 0; i \u003c 10; i++)\n            cout \u003c\u003c arr1[i] \u003c\u003c \" \";\n    }\n};\n\nint main() {\n    Arr arr;\n    arr.reverse();\n}\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### Left Shift / Rotation?\n\nMove elements one position **left**.\n\n- The **first element** moves to the **last position**.\n- Used in **image sliders** and **circular queues**.\n\n- **Time Complexity:** `O(n)`\n\n```cpp\n#include \u003ciostream\u003e\nusing namespace std;\n\nclass Arr {\n  public:\n    int A[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n\n    void rotate() {\n        int temp = A[0];\n        for (int i = 0; i \u003c 9; i++) {\n            A[i] = A[i + 1];\n        }\n        A[9] = temp;\n\n        for (int i = 0; i \u003c 10; i++)\n            cout \u003c\u003c A[i] \u003c\u003c \" \";\n    }\n};\n\nint main() {\n    Arr A;\n    A.rotate();\n}\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### Right Shift / Rotation?\n\nMove elements one position **right**.\n\n- The **last element** moves to the **first position**.\n\n- **Time Complexity:** `O(n)`\n\n```cpp\n#include \u003ciostream\u003e\nusing namespace std;\n\nclass Arr {\n  public:\n    int A[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n\n    void rotate() {\n        int temp = A[9];\n        for (int i = 9; i \u003e 0; i--) {\n            A[i] = A[i - 1];\n        }\n        A[0] = temp;\n\n        for (int i = 0; i \u003c 10; i++)\n            cout \u003c\u003c A[i] \u003c\u003c \" \";\n    }\n};\n\nint main() {\n    Arr A;\n    A.rotate();\n}\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### Insert into Sorted Array?\n\nThis function inserts a given value into a **sorted array** while maintaining its sorted order.\n\n- **Time Complexity:** `O(n)`\n\n```cpp\nvoid insertIntoSorted(int value) {\n    int i = length - 1;\n\n    while (i \u003e= 0 \u0026\u0026 A[i] \u003e value) {\n        A[i + 1] = A[i];\n        i--;\n    }\n\n    A[i + 1] = value;\n    length++;\n}\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### Check if an Array is Sorted?\n\nThis function checks whether a given array is sorted in **ascending order**.\n\n- **Time Complexity:** `O(n)`\n\n```cpp\nbool isSorted() {\n    for (int i = 0; i \u003c 9; i++) {\n        if (A[i] \u003e A[i + 1]) {\n            return false;\n        }\n    }\n    return true;\n}\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### Arranging Negative Numbers on Left Side?\n\nThis function rearranges the array so that all **negative numbers** are placed on the **left side**, while the **non-negative numbers** remain on the right.\n\n- **Time Complexity:** `O(n)`\n\n```cpp\nvoid adjust() {\n    int i = 0, j = 9;\n    while (i \u003c j) {\n        while (A[i] \u003c 0) { i++; }\n        while (A[j] \u003e= 0) { j--; }\n        if (i \u003c j) {\n            int temp = A[i];\n            A[i] = A[j];\n            A[j] = temp;\n        }\n    }\n}\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### Merge Arrays?\n\n#### Merging Two Sorted Arrays\n- Combines two **sorted arrays** into one sorted array.\n- Uses a **two-pointer technique** to efficiently merge the arrays.\n\n- **Time Complexity:** `O(n + m)`, where `n` and `m` are the lengths of the arrays.\n\n```cpp\n#include \u003ciostream\u003e\nusing namespace std;\n\nclass Array {\npublic:\n    int A[5] = {1, 4, 7, 9, 10};\n    int B[5] = {2, 3, 5, 6, 8};\n    int C[10]; // Merged array\n    int length = 10;\n\n    void merge() {\n        int i = 0, j = 0, k = 0;\n\n        while (i \u003c 5 \u0026\u0026 j \u003c 5) {\n            if (A[i] \u003c= B[j]) {\n                C[k++] = A[i++];\n            } else {\n                C[k++] = B[j++];\n            }\n        }\n\n        while (i \u003c 5) {\n            C[k++] = A[i++];\n        }\n\n        while (j \u003c 5) {\n            C[k++] = B[j++];\n        }\n    }\n\n    void print() {\n        for (int i = 0; i \u003c length; i++)\n            cout \u003c\u003c C[i] \u003c\u003c \" \";\n        cout \u003c\u003c endl;\n    }\n};\n\nint main() {\n    Array arr;\n    arr.merge();\n    arr.print();\n}\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### Set Operations (Union, Intersection, Difference)?\n\n#### 1. Union of Two Arrays\n\n##### Unsorted Arrays\n\n- Copy all elements of the first array (A) into the result array (C).\n- Iterate through the second array (B).\n- If an element from B is not already present in C, add it.\n\n- **Time Complexity:** O(m * n) (for checking duplicates)\n\n```cpp\n#include\u003ciostream\u003e\nusing namespace std;\n\nclass Array{\n    public:\n      int A[5] = {2, 4, 1, 5, 10};\n      int B[5] = {3, 4, 1, 2, 9};\n      int C[10];\n      int length = 0;\n\n      void UNION() {\n          for(int i = 0; i \u003c 5; i++)\n              C[length++] = A[i];\n          for(int i = 0; i \u003c 5; i++){\n              bool found = false;\n              for(int j = 0; j \u003c length; j++){\n                  if(B[i] == C[j]){\n                      found = true;\n                      break;\n                  }\n              }\n              if(!found)\n                  C[length++] = B[i];\n          }\n      }\n\n      void print(){\n          for(int i = 0; i \u003c length; i++)\n              cout \u003c\u003c C[i] \u003c\u003c \" \";\n      }\n};\n\nint main()\n{\n    Array A;\n    A.UNION();\n    A.print();\n}\n```\n\n##### Sorted Arrays\n\n- Use two pointers i and j to traverse both arrays.\n- Compare elements and add the smaller one to C.\n- If they are equal, add one and move both pointers forward.\n- Add remaining elements of either array.\n\n- **Time Complexity:** O(m + n) (since both arrays are traversed once)\n\n```cpp\n#include\u003ciostream\u003e\nusing namespace std;\nclass Array{\n  public:\n    int A[5] = {1, 4, 7, 8, 10};\n    int B[5] = {2, 4, 5, 7, 8};\n    int C[10];\n    int k = 0;\n\n      void UNION() {\n         int i = 0, j = 0;\n\n         while(i \u003c 5 \u0026\u0026 j \u003c 5){\n             if(A[i] \u003c B[j]){\n                 C[k++] = A[i++];\n             }else if(A[i] \u003e B[j]){\n                 C[k++] = B[j++];\n             }else{\n                 C[k++] = A[i];\n                 i++; j++;\n             }\n         }\n\n         while(i \u003c 5)\n             C[k++] = A[i++];\n         while(j \u003c 5)\n             C[k++] = B[j++];\n      }\n\n      void print(){\n          for(int i = 0; i \u003c k; i++)\n              cout \u003c\u003c C[i] \u003c\u003c \" \";\n      }\n};\n\nint main()\n{\n    Array A;\n    A.UNION();\n    A.print();\n}\n```\n\n#### 2. Intersection of Two Arrays\n\n##### Unsorted Arrays\n\n- Iterate through A and B, checking for common elements.\n- Store them in C if found.\n\n- **Time Complexity:** O(m * n) (brute force comparison)\n\n```cpp\nvoid INTERSECTION(){\n    for(int i = 0; i \u003c 5; i++){\n        for(int j = 0; j \u003c 5; j++){\n            if(A[i] == B[j]){\n                C[k++] = A[i];\n            }\n        }\n    }\n}\n```\n\n##### Sorted Arrays\n\n- Use two pointers i and j.\n- If A[i] == B[j], store in C.\n- Otherwise, increment the smaller pointer.\n\n- **Time Complexity:** O(m + n)\n\n```cpp\nvoid INTERSECTION(){\n    int i = 0, j = 0;\n    while(i \u003c 5 \u0026\u0026 j \u003c 5){\n        if(A[i] \u003c B[j]){\n            i++;\n        }else if(A[i] \u003e B[j]){\n            j++;\n        }else{\n            C[k++] = A[i++];\n            j++;\n        }\n    }\n}\n```\n\n#### 3. Difference of Two Arrays\n\n##### Unsorted Arrays\n\n- Iterate through A, checking if each element exists in B.\n- If not, add to C.\n\n**Time Complexity:** O(m * n) (brute force search)\n\n```cpp\nvoid DIFFERENCE(){\n    for(int i = 0; i \u003c 5; i++){\n        bool isFound = false;\n        for(int j = 0; j \u003c 5; j++){\n            if(A[i] == B[j]){\n                isFound = true;\n                break;\n            }\n        }\n        if(!isFound){\n            C[k++] = A[i];\n        }\n    }\n}\n```\n\n##### Sorted Arrays\n\n- Use two pointers i and j.\n- If A[i] is smaller, add it to C.\n- If equal, skip both.\n- Append remaining elements of A.\n\n- **Time Complexity:** O(m + n)\n\n```cpp\nvoid DIFFERENCE(){\n    int i = 0, j = 0;\n\n    while(i \u003c 5 \u0026\u0026 j \u003c 5){\n        if(A[i] \u003c B[j]){\n            C[k++] = A[i++];\n        }else if(A[i] \u003e B[j]){\n            j++;\n        }else{\n            i++;\n            j++;\n        }\n    }\n\n    while(i \u003c 5)\n        C[k++] = A[i++];\n}\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### Find Missing Element (Single Missing, Multiple Missing)?\n\n#### 1. Single Missing Element from Natural Numbers (Sorted Array)\n\n- **From 1 to n (First n Natural Numbers):**\n\n```cpp\nvoid Array::missingElement(){\n    int sum = 10 * (10 + 1) / 2;\n    int s;\n    for(int i = 0; i \u003c 10; i++)\n        s += A[i];\n\n    cout \u003c\u003c \"Missing element is: \" \u003c\u003c (sum - s);\n};\n```\n\n- **From k to n:**\n\n```cpp\nvoid Array::missingElement(){\n    int diff = A[0] - 0;\n\n    for(int i = 0; i \u003c 10; i++){\n        if(A[i] - i != diff){\n            cout \u003c\u003c \"Missing element is: \" \u003c\u003c (diff + i) \u003c\u003c endl;\n            break;\n        }\n    }\n};\n// Add index + difference\n```\n\n#### 2. Multiple Missing Elements from Unsorted Array\n\n- This procedure uses a hash table / bit set, which operates in constant time.\n- When searching for missing elements, a hash table is a preferred choice if feasible.\n- When using this technique, the required space should be equal to the maximum value of the array. If space is constrained, this approach may not be suitable.\n\n```cpp\nvoid Array::missingElements(){\n    int B[14]; // Maximum element of array\n    for(int i = 0; i \u003c 14; i++)\n        B[A[i]] = 1;\n    for(int i = 0; i \u003c 14; i++)\n        if(B[i] == 0)\n           cout \u003c\u003c \"Missing element: \" \u003c\u003c i \u003c\u003c endl;\n}\n```\n\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### Find Duplicate Elements?\n\n#### 1. Finding Duplicates in a Sorted Array\n- If an element appears **more than once**, it should be printed **only once**.\n\n```cpp\nvoid duplicateElements(){\n    int lastDuplicate = 0;\n    for(int i = 0; i \u003c 10 - 1; i++){\n        if(A[i] == A[i + 1] \u0026\u0026 lastDuplicate != A[i]){\n            cout \u003c\u003c \"Duplicate element: \" \u003c\u003c A[i] \u003c\u003c endl;\n            lastDuplicate = A[i];\n        }\n    }\n}\n```\n\n#### 2. Counting Duplicates in a Sorted Array\n- Counts how many times each element appears in a sorted array.\n\n```cpp\nvoid countDuplicates(){\n    for(int i = 0; i \u003c 10 - 1; i++){\n        if(A[i] == A[i + 1]){\n            int j = i + 1;\n            while(A[j] == A[i]) j++;\n            cout \u003c\u003c A[i] \u003c\u003c \" appears \" \u003c\u003c j - i \u003c\u003c \" times.\" \u003c\u003c endl;\n            i = j - 1;\n        }\n    }\n}\n```\n\n#### 3. Counting Duplicates Using a Hash Table (Sorted Array)\n\n```cpp\nvoid countDuplicates(){\n    for(int i = 0; i \u003c 10 - 1; i++){\n        if(A[i] == A[i + 1]){\n            int j = i + 1;\n            while(A[j] == A[i]) j++;\n            cout \u003c\u003c A[i] \u003c\u003c \" \" \u003c\u003c j - i \u003c\u003c endl;\n            i = j - 1;\n        }\n    }\n}\n```\n\n#### 4. Finding Duplicates in an Unsorted Array\n- Uses brute force method, setting duplicate values to -1.\n\n```cpp\nvoid findDuplicateUnsort(){\n    for(int i = 0; i \u003c 10 - 1; i++){\n        int count = 1;\n        if(A[i] != -1){\n            for(int j = i + 1; j \u003c 10; j++){\n                if(A[i] == A[j]){\n                    count++;\n                    A[j] = -1;\n                }\n            }\n            if(count \u003e 1){\n                cout \u003c\u003c \"Duplicate element \" \u003c\u003c A[i] \u003c\u003c \" appears \" \u003c\u003c count \u003c\u003c \" times.\" \u003c\u003c endl;\n            }\n        }\n    }\n}\n```\n\n#### 5. Finding Duplicates Using a Hash Table (Unsorted Array)\n\n```cpp\nvoid findDuplicateUnsort(){\n    int B[10] = {0};\n    for(int i = 0; i \u003c 10; i++)\n        B[A[i]]++;\n    for(int i = 0; i \u003c 10; i++)\n        if(B[i] \u003e 1)\n            cout \u003c\u003c \"Duplicate element \" \u003c\u003c i \u003c\u003c \" appears \" \u003c\u003c B[i] \u003c\u003c \" times.\" \u003c\u003c endl;\n}\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### Finding a Pair with Sum K?\n\n#### 1. Finding a Pair of Elements with Sum K (Sorted Array)\nThis approach uses the **two-pointer technique** to find a pair whose sum equals `k`.\n- If the sum is equal to `k`, the pair is printed.\n- If the sum is less than `k`, increment `i` (move right).\n- If the sum is greater than `k`, decrement `j` (move left).\n\n- **Time Complexity:** `O(n)`\n\n```cpp\nvoid Array::findPair(int k){\n    int i = 0, j = 10 - 1;\n    while (i \u003c j) {\n        if(A[i] + A[j] == k){\n            cout \u003c\u003c \"Pair found: \" \u003c\u003c A[i] \u003c\u003c \" and \" \u003c\u003c A[j] \u003c\u003c endl;\n            i++; j--;\n        } else if(A[i] + A[j] \u003c k){\n            i++;\n        } else {\n            j--;\n        }\n    }\n}\n```\n\n#### 2. Finding a Pair of Elements with Sum K (Unsorted Array)\nThis approach **checks all possible pairs** in a nested loop to find the sum `k`.\n- It iterates through the array, comparing each element with every other element.\n- If a pair with sum `k` is found, it is printed.\n\n- **Time Complexity:** `O(n²)`\n\n```cpp\nvoid Array::findPair(int k){\n    for(int i = 0; i \u003c 10 - 1; i++){\n        for(int j = i + 1; j \u003c 10; j++){\n            if(A[i] + A[j] == k){\n                cout \u003c\u003c \"Pair found: \" \u003c\u003c A[i] \u003c\u003c \" and \" \u003c\u003c A[j] \u003c\u003c endl;\n            }\n        }\n    }\n}\n```\n\n#### 3. Finding a Pair of Elements with Sum K (Using Hash Table)\nThis approach **uses an auxiliary array (hash table)** to store values and find the sum efficiently.\n\n#### How It Works:\n- It iterates through the array, checking if `k - A[i]` exists in the hash table.\n- If found, it prints the pair.\n- Otherwise, it marks `A[i]` as visited in the hash table.\n\n- **Time Complexity:** `O(n)`\n\n```cpp\nvoid Array::findPair(int k){\n    int B[10] = {0};\n\n    for(int i = 0; i \u003c 10; i++){\n        if(B[k - A[i]] != 0)\n            cout \u003c\u003c \"Pair found: \" \u003c\u003c A[i] \u003c\u003c \" and \" \u003c\u003c k - A[i] \u003c\u003c endl;\n        B[A[i]]++;\n    }\n}\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### Reverse an Array?\n\nReversing an array can be done in different segments:\n\n#### 1. Reverse `[1, k]`\nThis function reverses the elements from index `1` to `k` (0-based indexing).\n\n```cpp\nvoid reverseOneToK(int k){\n    for(int i = 0, j = k - 1; i \u003c k / 2; i++, j--){\n        int c = A[i];\n        A[i] = A[j];\n        A[j] = c;\n    }\n}\n```\n\n#### 2. Reverse `[k + 1, n]`\nThis function reverses elements from index `k + 1` to `n`, which means reversing the latter part of the array.\n\n```cpp\nvoid reverseFromKPlusOne(int k) {\n  for (int i = k + 1, j = size - 1; i \u003c j; i++, j--) {\n      int temp = A[i];\n      A[i] = A[j];\n      A[j] = temp;\n  }\n}\n```\n\n#### 3. Reverse `[1, n]`\nThis function reverses the entire array.\n\n```cpp\nvoid reverseOneToN(){\n    for(int i = 0, j = 10 - 1; i \u003c j; i++, j--){\n        int c = A[i];\n        A[i] = A[j];\n        A[j] = c;\n    }\n}\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### Find Two Elements with Difference Equal to S in a Sorted Array?\n\n```Array in increasing order, we want to find two elements having difference equal to (s)```\n\n- Works for sorted arrays.\n- Uses two pointers (`i` and `j`).\n- If difference equals `s`, prints the pair.\n- If difference is less than `s`, moves `j` forward.\n- If difference is greater than `s`, moves `i` forward.\n\n#### Time Complexity: `O(n)`\n\n```cpp\nvoid findDifference(int s) {\n    int i = 0, j = 1;\n    while (j \u003c 10) {\n        if ((A[j] - A[i]) == s) {\n            cout \u003c\u003c \"Difference found with: \" \u003c\u003c A[j] \u003c\u003c \" - \" \u003c\u003c A[i] \u003c\u003c endl;\n            i++;\n            j++;\n        } else if ((A[j] - A[i]) \u003c s) {\n            j++;\n        } else {\n            i++;\n        }\n    }\n}\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### Finding Minimum and Maximum in a Single Scan?\n\n```cpp\nvoid minAndMax(){\n    int min = A[0], max = A[0];\n\n    for(int i = 1; i \u003c 10; i++){\n        if(A[i] \u003c min)\n            min = A[i];\n        else if(A[i] \u003e max)\n            max = A[i];\n    }\n\n    cout \u003c\u003c \"Minimum: \" \u003c\u003c min \u003c\u003c \", Maximum: \" \u003c\u003c max \u003c\u003c endl;\n}\n```\n\n- **Best Case:** When array is in descending order (1 comparison per iteration).\n- **Worst Case:** When min and max are at opposite ends.\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### Find Array Elements that are Neither Minimum nor Maximum?\n\n#### 1. Simple Conditional Check\n```cpp\nvoid findNum() {\n   if(A[0] \u003e A[1] \u0026\u0026 A[0] \u003c A[2])\n       cout \u003c\u003c \"Number: \" \u003c\u003c A[0];\n   else if(A[1] \u003e A[0] \u0026\u0026 A[1] \u003c A[2])\n       cout \u003c\u003c \"Number: \" \u003c\u003c A[1];\n   else\n       cout \u003c\u003c \"Number: \" \u003c\u003c A[2];\n}\n```\n\n#### 2. Generalized Approach for Larger Arrays\n\n```cpp\nvoid findMiddleElements(int A[], int n) {\n    int minVal = INT_MAX, maxVal = INT_MIN;\n\n    // Finding minimum and maximum values\n    for(int i = 0; i \u003c n; i++) {\n        if(A[i] \u003c minVal) minVal = A[i];\n        if(A[i] \u003e maxVal) maxVal = A[i];\n    }\n\n    cout \u003c\u003c \"Elements neither minimum nor maximum: \";\n    for(int i = 0; i \u003c n; i++) {\n        if(A[i] != minVal \u0026\u0026 A[i] != maxVal)\n            cout \u003c\u003c A[i] \u003c\u003c \" \";\n    }\n    cout \u003c\u003c endl;\n}\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### Find 2nd Maximum or Minimum Element?\n\n```cpp\n// Maximum\nvoid secondMaximum(){\n    int first = INT_MIN, second = INT_MIN;\n    for(int i = 0; i \u003c 10; i++){\n        if(A[i] \u003e first){\n            second = first;\n            first = A[i];\n        } else if(A[i] \u003e second \u0026\u0026 A[i] != first){\n            second = A[i];\n        }\n    }\n    cout \u003c\u003c \"Second maximum value: \" \u003c\u003c second \u003c\u003c endl;\n}```\n\n```cpp\n// Minimum\nvoid secondMinimum(){\n    int first = INT_MAX, second = INT_MAX;\n    for(int i = 0; i \u003c 10; i++){\n        if(A[i] \u003c first){\n            second = first;\n            first = A[i];\n        } else if(A[i] \u003c second \u0026\u0026 A[i] != first){\n            second = A[i];\n        }\n    }\n    cout \u003c\u003c \"Second minimum value: \" \u003c\u003c second \u003c\u003c endl;\n}\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### Find Elements in Range (0-100) with Frequency \u003e 50\n\n- Given an array of elements within the range **0 to 100**, find the **frequency of elements greater than 50** and display the count of each occurrence.\n\n#### Approach\n- We initialize an array `temp[50]` to store the frequency of numbers **greater than 50** (i.e., numbers between **51 to 100**).\n- We read `n` elements from user input.\n- If the number is **greater than 50**, we increment its respective index in `temp[]`.\n- Finally, we display the numbers and their corresponding frequency.\n\n```cpp\n#include \u003ciostream\u003e\nusing namespace std;\n\nclass Array {\npublic:\n    int temp[50] = {0}; // Frequency array for numbers 51-100\n\n    void elementsCounting() {\n        for (int i = 0; i \u003c 10; i++) { // Modify 10 based on input size\n            int element;\n            cin \u003e\u003e element;\n\n            if (element \u003e 50 \u0026\u0026 element \u003c= 100)\n                temp[element - 51]++; // Map 51-100 to 0-49 index\n        }\n    }\n\n    void display() {\n        for (int i = 0; i \u003c 50; i++) {\n            if (temp[i] != 0)\n                cout \u003c\u003c (i + 51) \u003c\u003c \" appears \" \u003c\u003c temp[i] \u003c\u003c \" times\" \u003c\u003c endl;\n        }\n    }\n};\n\nint main() {\n    Array A;\n    A.elementsCounting();\n    A.display();\n}\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n---\n---\n\n## Strings\n\n### Character Set\n\n- A character set is the set of characters that are supported by a programming language.\n- Computers do not directly understand characters, so numeric codes are assigned to characters.\n- These numeric codes are standardized globally, known as ASCII and Unicode.\n- Standardized by `American National Standards Institute (ANSI)` and `ISO`.\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### ASCII\n\n- Total ASCII codes: `128` (0-127)\n- `A-Z` ASCII codes: `65-90`\n- `a-z` ASCII codes: `97-122`\n- `0-9` ASCII codes: `48-57`\n- Special characters: `Enter = 10`, `Space = 13`, `Esc = 27`\n- Each symbol/character takes `7 bits` or `1 byte`\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### Unicode\n\n- Supports all languages worldwide.\n- Uses `16 bits` or `2 bytes`.\n- Represented in hexadecimal format.\n\n### Character array\n- `char A[5];`\n- `char A[5] = {65, 66, 67, 68, 69};`\n- `char A[5] = {'A', 'B', 'C', 'D', 'E'}`\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### Difference Between Character Set and Strings\n- A **character set** is a collection of characters assigned with unique numeric codes.\n- A **string** is a sequence of characters that ends with a null character (`\\0`).\n\n```cpp\n#include \u003ciostream\u003e\nusing namespace std;\n\nint main() {\n    char charSet[] = {65, 66, 67, 68, 69}; // Character Set (ASCII values for A-E)\n    char str[] = \"ABCDE\"; // String with \\0 at the end\n\n    cout \u003c\u003c \"Character Set: \";\n    for (char c : charSet) {\n        cout \u003c\u003c c \u003c\u003c \" \";\n    }\n    cout \u003c\u003c \"\\nString: \" \u003c\u003c str \u003c\u003c endl;\n    return 0;\n}\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### Strings\n- A string is a sequence of characters terminated by a special character `\\0` (null character).\n- The `\\0` character acts as a string delimiter.\n\n  ```cpp\n  char A[6] = \"Hello\"; // Automatically adds '\\0' at the end\n  ```\n- Without `\\0`, a character array remains just an array of characters, not a string.\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### How to find Length of string?\n\n- We cannot calculate the size of a string using `array - 1` because the string may have fewer elements than the total allocated size.\n- In C and C++, when you initialize a character array with a string literal like \"ABDUL AHAD\", the compiler automatically appends a null terminator ('\\0') at the end of the string.\n  - So, when you declare `char A[] = \"ABDUL AHAD\";`, the memory layout looks like this:\n    - | 'A' | 'B' | 'D' | 'U' | 'L' | 'A' | ' ' | 'H' | 'A' | 'D' | '\\0' |\n\n```cpp\nchar A[] = \"ABDUL AHAD\";\ncout \u003c\u003c A \u003c\u003c endl;\nchar B[5] = {'A', 'B', 'C', 'D', '\\0'};\ncout \u003c\u003c B \u003c\u003c endl;\nchar C[] = {'A', 'B', 'C', 'D', '\\0'};\ncout \u003c\u003c C \u003c\u003c endl;\nint length = 0;\nfor(int i = 0; A[i] != '\\0'; i++)\n    length++;\ncout \u003c\u003c \"Length of A: \" \u003c\u003c length;\n```\n\n#### Another approach using a function:\n\n```cpp\nint length(char str[]) {\n    int i = 0;\n    while (str[i] != '\\0') {\n        i++;\n    }\n    return i;\n}\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### How to change case of strings?\n\nChanging the case of a string means converting **uppercase letters to lowercase** and **lowercase letters to uppercase**.\n- In **ASCII**, uppercase letters ('A' to 'Z') range from **65 to 90**.\n- Lowercase letters ('a' to 'z') range from **97 to 122**.\n- The difference between uppercase and lowercase letters is **32** (`'A' + 32 = 'a'` and `'a' - 32 = 'A'`).\n\n#### Convert Uppercase to Lowercase\n\n```cpp\n#include \u003ciostream\u003e\nusing namespace std;\n\nint main() {\n    char A[] = \"ABDUL AHAD\";\n\n    // Convert to lowercase\n    for (int i = 0; A[i] != '\\0'; i++) {\n        A[i] = char(A[i] + 32);\n    }\n\n    cout \u003c\u003c A \u003c\u003c endl; // Output: abdul ahad\n\n    // Convert the first letter back to uppercase\n    A[0] = char(A[0] - 32);\n\n    cout \u003c\u003c A; // Output: Abdul ahad\n}\n```\n\n#### Convert Lowercase to Uppercase and Vice Versa\n\n- This program swaps the case of each character.\n\n```cpp\n#include \u003ciostream\u003e\nusing namespace std;\n\nint main() {\n    char A[] = \"ABDUL AHAD\";\n\n    // Toggle case (uppercase → lowercase, lowercase → uppercase)\n    for (int i = 0; A[i] != '\\0'; i++) {\n        if (A[i] \u003e= 97 \u0026\u0026 A[i] \u003c= 122) // If lowercase\n            A[i] -= 32;\n        else if (A[i] \u003e= 65 \u0026\u0026 A[i] \u003c= 90) // If uppercase\n            A[i] += 32;\n    }\n\n    char B[] = \"cHiLli\";\n\n    for (int i = 0; B[i] != '\\0'; i++) {\n        if (B[i] \u003e= 'a' \u0026\u0026 B[i] \u003c= 'z') // If lowercase\n            B[i] -= 32;\n        else if (B[i] \u003e= 'A' \u0026\u0026 B[i] \u003c= 'Z') // If uppercase\n            B[i] += 32;\n    }\n\n    cout \u003c\u003c A \u003c\u003c \" \" \u003c\u003c B;\n    // Output: abdul ahad ChIlLI\n}\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### How to count words, vowels and consonants in a string?\n\nThis program calculates:\n1. **Word Count**: A word is identified when a space is followed by a non-space character.\n2. **Vowel Count**: Characters `a, e, i, o, u` (both uppercase and lowercase).\n3. **Consonant Count**: Any letter that is not a vowel.\n\n```cpp\n#include \u003ciostream\u003e\nusing namespace std;\n\nint main() {\n    char A[] = \"We are all Palestinian\";\n    int wordCount = 0, vowelCount = 0, consonantCount = 0;\n\n    for (int i = 0; A[i] != '\\0'; i++) {\n        // Counting words (checking spaces between words)\n        if (A[i] == ' ' \u0026\u0026 A[i - 1] != ' ')\n            wordCount++;\n\n        // Counting vowels\n        if (A[i] == 'a' || A[i] == 'e' || A[i] == 'i' || A[i] == 'o' || A[i] == 'u' ||\n            A[i] == 'A' || A[i] == 'E' || A[i] == 'I' || A[i] == 'O' || A[i] == 'U') {\n            vowelCount++;\n        }\n        // Counting consonants (any alphabet that is not a vowel)\n        else if ((A[i] \u003e= 65 \u0026\u0026 A[i] \u003c= 90) || (A[i] \u003e= 97 \u0026\u0026 A[i] \u003c= 122)) {\n            consonantCount++;\n        }\n    }\n\n    cout \u003c\u003c \"Total words: \" \u003c\u003c wordCount + 1 \u003c\u003c \" ,Vowels: \" \u003c\u003c vowelCount \u003c\u003c \" ,Consonants: \" \u003c\u003c consonantCount;\n}\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### How to validate a string?\n\nThis program checks whether a given string is **valid** by ensuring it contains only:\n1. **Digits (0-9)**\n2. **Uppercase letters (A-Z)**\n3. **Lowercase letters (a-z)**\n\n- If the string contains any special characters (e.g., `@, *, #, !`), it is considered **invalid**.\n\n```cpp\n#include \u003ciostream\u003e\nusing namespace std;\n\nint validate(char A[]) {\n    for (int i = 0; A[i] != '\\0'; i++) {\n        // Checking if the character is NOT a digit, uppercase letter, or lowercase letter\n        if (!(A[i] \u003e= 48 \u0026\u0026 A[i] \u003c= 57) \u0026\u0026 !(A[i] \u003e= 65 \u0026\u0026 A[i] \u003c= 90) \u0026\u0026 !(A[i] \u003e= 97 \u0026\u0026 A[i] \u003c= 122))\n            return 0; // Invalid string\n    }\n    return 1; // Valid string\n}\n\nint main() {\n    char A[] = \"ABDULAHAD786*ali\";  // String to validate\n    if (validate(A))\n        cout \u003c\u003c \"Valid string!\";\n    else\n        cout \u003c\u003c \"Not a valid string!\";\n}\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### How to Reverse a String?\n\nReversing a string means rearranging its characters in the opposite order. We can achieve this using:\n1. **Extra Array Method**: Storing the reversed string in a separate array.\n2. **Swapping Method**: Swapping characters in the same array.\n\n#### **Method 1: Using an Extra Array**\n- First, find the **length** of the string.\n- Then, store characters in reverse order in a new array.\n\n```cpp\n#include \u003ciostream\u003e\nusing namespace std;\n\nint main() {\n    char A[] = \"CHILLI\";\n    int i;\n\n    // Finding string length\n    for(i = 0; A[i] != '\\0'; i++) {};\n\n    char B[i];  // Creating new array to store reversed string\n    i = i - 1;  // Adjusting index to last character\n\n    // Storing characters in reverse order\n    for(int j = 0; i \u003e= 0; i--, j++)\n        B[j] = A[i];\n\n    cout \u003c\u003c \"Reversed string: \" \u003c\u003c B;\n}\n```\n\n#### **Method 2: Swapping in the Same Array**\n- Using two pointers: One at the start, another at the end.\n- Swap characters until pointers meet in the middle.\n\n```cpp\n#include \u003ciostream\u003e\nusing namespace std;\n\nint main() {\n    char A[] = \"CHILLI\";\n    int i, j;\n\n    // Finding string length\n    for(j = 0; A[j] != '\\0'; j++) {};\n    j--;  // Move to last character\n\n    // Swapping characters\n    for(i = 0; i \u003c j; i++, j--) {\n        char c = A[i];\n        A[i] = A[j];\n        A[j] = c;\n    }\n\n    cout \u003c\u003c \"Reversed string: \" \u003c\u003c A;\n}\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### How to compare strings and check palindrome?\n\n#### **1. Comparing Strings**\nString comparison determines which string is lexicographically larger, smaller, or equal.\n\n- Iterate through both strings **character by character**.\n- Stop at the first mismatched character.\n- Compare their ASCII values:\n  - If `A[i] \u003e B[j]`, `A` is larger.\n  - If `A[i] \u003c B[j]`, `A` is smaller.\n  - If all characters match, the strings are equal.\n\n```cpp\n#include \u003ciostream\u003e\nusing namespace std;\n\nint main() {\n    char A[] = \"APPLE\";\n    char B[] = \"BANANA\";\n    int i, j;\n\n    // Compare characters one by one\n    for(i = 0, j = 0; A[i] != '\\0' \u0026\u0026 B[j] != '\\0'; i++, j++)\n        if(A[i] != B[j])\n            break;\n\n    if(A[i] \u003e B[j])\n        cout \u003c\u003c \"A is larger\";\n    else if(A[i] \u003c B[j])\n        cout \u003c\u003c \"A is smaller\";\n    else\n        cout \u003c\u003c \"Both strings are equal!\";\n}\n```\n\n#### **2. Checking if a String is a Palindrome**\n\nA **palindrome** is a string that reads the same **forward and backward**.\n\n- **\"MADAM\"**, **\"RACECAR\"** are palindromes.\n- **\"HELLO\"**, **\"WORLD\"** are not palindromes.\n\n1. **Reverse** the string and store it in another array.\n2. **Compare** the original and reversed strings **character by character**.\n3. If all characters match, **it's a palindrome**.\n\n```cpp\n#include \u003ciostream\u003e\nusing namespace std;\n\nint main() {\n    char A[] = \"MADAM\";\n    int i;\n\n    // Step 1: Find string length\n    for(i = 0; A[i] != '\\0'; i++) {}\n\n    char B[i + 1];  // Extra space for null terminator\n    B[i] = '\\0';  // End reversed string with null character\n\n    // Step 2: Store reversed string\n    for(int j = 0; i \u003e 0; i--, j++) {\n        B[j] = A[i - 1];\n    }\n\n    // Step 3: Compare original and reversed strings\n    for(i = 0; A[i] != '\\0'; i++) {\n        if(A[i] != B[i]) {\n            cout \u003c\u003c \"Not a palindrome\\n\";\n            return 0;\n        }\n    }\n\n    cout \u003c\u003c \"Palindrome\\n\";\n}\n```\n\n#### **3. Alternative: Two-Pointer Palindrome Check**\n\n- A more efficient approach is to use two pointers, one at the start and one at the end, and compare characters.\n\n```cpp\n#include \u003ciostream\u003e\nusing namespace std;\n\nint main() {\n    char A[] = \"MADAM\";\n    int i, j;\n\n    // Find string length\n    for(j = 0; A[j] != '\\0'; j++) {};\n    j--;  // Adjust for index\n\n    // Compare first and last characters\n    for(i = 0; i \u003c j; i++, j--) {\n        if(A[i] != A[j]) {\n            cout \u003c\u003c \"Not a palindrome\\n\";\n            return 0;\n        }\n    }\n\n    cout \u003c\u003c \"Palindrome\\n\";\n}\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### How to find duplicates in strings?\n\n  Finding duplicate characters in a string helps in **text processing, compression, and data validation**.\n\n#### **Methods to Find Duplicates**\n1. **Using Nested Loops** (Brute Force) → **O(n²) Time Complexity**\n2. **Using Hash Tables** (Efficient for lowercase letters) → **O(n) Time Complexity**\n\n\n#### **1. Brute Force Approach (Nested Loops)**\n\n- Compare each character with all previous characters.\n\n```cpp\n#include \u003ciostream\u003e\nusing namespace std;\n\nint main() {\n    char A[] = \"Finding\";\n\n    for(int i = 0; A[i] != '\\0'; i++) {\n        for(int j = 0; j \u003c i; j++) {\n            if(A[i] == A[j]) {\n                cout \u003c\u003c \"Duplicate element: \" \u003c\u003c A[i] \u003c\u003c endl;\n                break; // Stop checking once a duplicate is found\n            }\n        }\n    }\n}\n```\n\n#### **2. Efficient Approach Using Hash Tables**\n\n1. Create an **array of size 26** (for lowercase letters).\n2. Traverse the string and count occurrences of each character.\n3. Print characters that appear **more than once**.\n\n```cpp\n#include \u003ciostream\u003e\nusing namespace std;\n\nint main() {\n    char A[] = \"finding\"; // Lowercase string\n    int B[26] = {0};  // Hash table initialized with 0\n\n    // Count character occurrences\n    for(int i = 0; A[i] != '\\0'; i++) {\n        B[A[i] - 'a']++;\n    }\n\n    // Display duplicates\n    for(int i = 0; i \u003c 26; i++) {\n        if(B[i] \u003e 1) {\n            cout \u003c\u003c char(i + 'a') \u003c\u003c \" appears \" \u003c\u003c B[i] \u003c\u003c \" times.\" \u003c\u003c endl;\n        }\n    }\n}\n```\n\n#### **3. Optimized Approach: Using Bit Manipulation**\n\n- **Faster** than other methods.\n- **Lower memory usage** (only a single integer).\n- Works **only for lowercase letters (a-z)**.\n\n```cpp\n#include \u003ciostream\u003e\nusing namespace std;\n\nint main() {\n    char A[] = \"finding\";\n    int checker = 0, x = 0;\n\n    for(int i = 0; A[i] != '\\0'; i++) {\n        x = 1 \u003c\u003c (A[i] - 'a');  // Create a bitmask\n\n        if((checker \u0026 x) \u003e 0) // Check if character already exists\n            cout \u003c\u003c \"Duplicate element: \" \u003c\u003c A[i] \u003c\u003c endl;\n        else\n            checker = checker | x;  // Mark character as seen\n    }\n}\n```\n\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### How to apply bitwise operations?\n\n#### **Why Use Bitwise Operations?**\n\nBitwise operations allow efficient manipulation of binary data. They are widely used in:\n- **Strings:** Checking for duplicate characters, toggling cases, etc.\n- **Integers:** Performing arithmetic and logical operations efficiently.\n\n\n#### **Types of Bitwise Operations**\n##### **1️. Left Shift (`\u003c\u003c`)**\n- Shifts bits **to the left** by a specified number of positions.\n- Fills the empty right positions with `0`s.\n- Effectively **multiplies** the number by `2^n`.\n\n```cpp\nint x = 5;      // 0000 0101\nint y = x \u003c\u003c 1; // 0000 1010  (5 * 2 = 10)\n```\n\n##### **2. Bitwise AND (`\u0026`) - Masking**\n- Used to check whether a specific bit is set (ON) or not.\n- If a bit is `1` in both operands, the result is `1`; otherwise, `0`.\n\n```cpp\nint x = 5;      // 0000 0101\nint y = 1;      // 0000 0001\nint result = x \u0026 y; // 0000 0001 (1)\n```\n\n- **Use Case:** Checking if a character has already appeared in a string.\n\n##### **3️. Bitwise OR (`|`) - Merging**\n- Used to set (turn ON) a bit at a specific position.\n- If a bit is `1` in either operand, the result is `1`.\n\n```cpp\nint x = 5;      // 0000 0101\nint y = 2;      // 0000 0010\nint result = x | y; // 0000 0111 (7)\n```\n\n- **Use Case:** Marking a character as \"seen\" in a string.\n\n##### **4. Finding Duplicate Characters in a String**\nThis method uses bitwise operations to detect duplicate characters efficiently.\n\n- Use a long integer (`H`) as a bit container.\n- Left shift (`\u003c\u003c`) to mark characters as seen.\n- Use AND (`\u0026`) to check if a character was already marked.\n- Use OR (`|`) to mark new characters as seen.\n\n```cpp\n#include \u003ciostream\u003e\nusing namespace std;\n\nint main() {\n    char A[] = \"Finding\";\n    long int H = 0, x = 0;\n\n    for(int i = 0; A[i] != '\\0'; i++) {\n        x = 1;\n        x = x \u003c\u003c (A[i] - 'a');  // Left shift based on character position\n\n        if((x \u0026 H) \u003e 0)  // Check if character is already seen\n            cout \u003c\u003c A[i] \u003c\u003c \" is a duplicate element!\" \u003c\u003c endl;\n        else\n            H = x | H;  // Mark character as seen\n    }\n}\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### How to check if strings are anagram?\n\nAn anagram is a word or phrase formed by rearranging the letters of a different word or phrase. In this approach, we check whether all the elements from string 1 are present in string 2.\n\n- First, check if the sizes of both strings are equal. If not, they are not anagrams.\n- Use an array of size 26 (for lowercase letters) to count occurrences of each character in the first string.\n- Traverse the second string and decrement the character count in the array.\n- If any value in the array becomes negative, the strings are not anagrams.\n- If all values are zero at the end, the strings are anagrams.\n\n```cpp\n#include \u003ciostream\u003e\nusing namespace std;\n\nint main() {\n    char A[] = \"finding\";\n    char B[] = \"dingfin\";\n\n    int i, C[26] = {0};\n    bool isAnagram = true;\n\n    // Count character occurrences in A\n    for(i = 0; A[i] != '\\0'; i++)\n        C[A[i] - 'a'] += 1;\n\n    // Compare with B\n    for(i = 0; B[i] != '\\0'; i++) {\n        C[B[i] - 'a'] -= 1;\n        if(C[B[i] - 'a'] \u003c 0) {\n            isAnagram = false;\n            cout \u003c\u003c \"Not Anagram\" \u003c\u003c endl;\n            break;\n        }\n    }\n\n    if(isAnagram \u0026\u0026 B[i] == '\\0')\n        cout \u003c\u003c \"Anagram\" \u003c\u003c endl;\n}\n```\n\n#### Complexity Analysis\n| Method | Time Complexity | Space Complexity |\n|--------|----------------|------------------|\n| Nested Loops | O(n²) | O(1) |\n| Hash Table | O(n) | O(1) |\n\n**Recommended Approach:** Using hash tables provides better performance compared to the nested loop method.\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### How to Find Permutation of Strings?\n\n- **Arrangement of a string.**\n\n- For `ABC`:\n  - Possible permutations: `ABC, ACB, BAC, BCA, CAB, CBA`\n  - Since there are `3` characters, the number of arrangements is `3!`.\n  - For `n` characters, the arrangement is `n!`.\n- **State Space Tree**: Imagine a tree where each branch represents a possible state of a problem, and the leaves show the results.\n- **Backtracking**: Going back and trying another path in the tree to explore different possibilities.\n\n\n- **Brute Force**: Trying every possible combination to find a solution.\n- **Recursion**: Using a procedure within itself to explore different paths, often used for backtracking.\n- **Dynamic Programming**: It's like a smarter brute force. It also tries different combinations but aims to find the best solution efficiently.\n\n- Use recursion to achieve backtracking.\n- With backtracking, we perform brute force.\n- Traverse in each call and pick characters that are not yet selected.\n- At the leaf node, prepare a string and display it.\n\n#### Method 1: Using Recursion with a Helper Array\n```cpp\n#include \u003ciostream\u003e\nusing namespace std;\n\nvoid perm(char s[], int k){\n    static char res[10];\n    static int A[10] = {0};\n    if(s[k] == '\\0'){\n        res[k] = '\\0';\n        cout \u003c\u003c res \u003c\u003c \" \";\n    }else{\n        for(int i = 0; s[i] != '\\0'; i++){\n            if(A[i] == 0){\n                res[i] = s[k];\n                A[i] = 1;\n                perm(s, k + 1);\n                A[i] = 0;\n            }\n        }\n    }\n}\n\nint main()\n{\n   char p[] = \"ABC\";\n   perm(p, 0);\n}\n```\n\n#### Method 2: Using Swapping\n```cpp\n#include \u003ciostream\u003e\nusing namespace std;\n\nvoid swap(char \u0026x, char \u0026y){\n    char z = x;\n    x = y;\n    y = z;\n}\n\nvoid perm(char p[], int l, int h){\n    if(l == h){\n        cout \u003c\u003c p \u003c\u003c \" \";\n    }else{\n        for(int i = l; i \u003c= h; i++) {\n            swap(p[l], p[i]);\n            perm(p, l + 1, h);\n            swap(p[l], p[i]);\n        }\n    }\n}\n\nint main()\n{\n   char p[] = \"ABC\";\n   perm(p, 0, 2);\n}\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n---\n---\n\n## Recursion\n\n### What is Recursion?\n\nRecursion is a programming concept where a function calls itself to solve a smaller version of the same problem.\n\n- Recursion breaks a problem into smaller sub-problems of the same type.\n- It follows the **LIFO (Last In, First Out)** principle.\n- Every recursive function must have a **base case** to prevent infinite recursion.\n- Recursion can be traced using a **tree diagram**.\n- It has two phases:\n  - **Calling phase** (function calls itself)\n  - **Returning phase** (function returns values)\n\n```cpp\nvoid fun(int num) {\n  if (num \u003e 0) {\n      cout \u003c\u003c num \u003c\u003c \" \"; // Prints in descending order\n      fun(num - 1); // Recursive call\n      cout \u003c\u003c num \u003c\u003c \" \"; // Prints in ascending order after returning from recursion\n  }\n}\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### How Recursion Works?\n\nRecursion follows these steps:\n1. Calls itself with a smaller input.\n2. Stops when it reaches the **base case**.\n3. Returns values in reverse order (returning phase).\n\nExample:\n```cpp\nvoid countDown(int n) {\n    if (n == 0) return; // Base case\n    cout \u003c\u003c n \u003c\u003c \" \";\n    countDown(n - 1); // Recursive call\n}\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### What are the Advantages \u0026 Disadvantages of Recursion?\n\n#### Advantages:\n- Easier to read and write for problems like tree traversal, DFS, etc.\n- Reduces complex problems into simpler sub-problems.\n\n#### Disadvantages:\n- Can be **slow** due to repeated function calls.\n- Uses **extra memory** (stack space).\n- Risk of **stack overflow** if recursion depth is too high.\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### How to Trace Recursive Functions?\n\nRecursion can be traced using a **tree diagram**.\n\n1. Identify the **base case** and **recursive case**.\n2. Expand each recursive call in a **tree-like structure**.\n3. Evaluate the base case first to stop recursion.\n4. Work your way **back up** to compute results.\n\n#### **Head Recursion** (Recursive Call First)\n```cpp\nvoid fun1(int n) {\n    if (n \u003e 0) {\n        cout \u003c\u003c n \u003c\u003c \" \";  // Print before recursive call\n        fun1(n - 1);\n    }\n}\nint main() {\n    fun1(3);\n}\n```\n\n**Tracing:**\n```\n        fun1(3)\n        /  \\\n Print 3    fun1(2)\n           /   \\\n    Print 2     fun1(1)\n                /   \\\n         Print 1     fun1(0) → Base Case (stops recursion)\n```\n\n#### **Tail Recursion** (Recursive Call First, Printing After Returning)\n```cpp\nvoid fun2(int n) {\n    if (n \u003e 0) {\n        fun2(n - 1);  // Recursive call first\n        cout \u003c\u003c n \u003c\u003c \" \";  // Print after recursion\n    }\n}\nint main() {\n    fun2(3);\n}\n```\n**Tracing:**\n```\n              fun2(3)\n              /\n        fun2(2)\n        /\n   fun2(1)\n   /\nfun2(0) → Base Case (stops recursion)\n   ├── Prints 1\n   ├── Prints 2\n   ├── Prints 3\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### What are the Phases of Recursion?\n\nRecursion has two phases:\n1. **Calling Phase**: Function calls itself.\n2. **Returning Phase**: Function returns values after reaching the base case.\n\n```cpp\nint fun(int num) {\n    if (num \u003e 0) {\n        cout \u003c\u003c num \u003c\u003c \" \"; // Calling Phase\n        fun(num - 1);\n        cout \u003c\u003c num \u003c\u003c \" \"; // Returning Phase\n    }\n}\n```\n\n**Two scenarios of recursion:**\n\n- Switch on the light (bulb) and go to the next room.\n\n```cpp\nvoid fun(int num) {\n    if (num \u003e 0) {\n        cout \u003c\u003c num \u003c\u003c \" \"; // Prints in descending order\n        fun(num - 1); // (*2) Returning time\n        cout \u003c\u003c num \u003c\u003c \" \"; // Prints in ascending order after returning from recursion\n    }\n}\n```\n\n- Go to the next room and then switch on the light (bulb).\n\n```cpp\nint fun2(int num){\n    if(num \u003e 0){\n        fun1(num - 1);\n        cout \u003c\u003c num \u003c\u003c \" \";\n    }\n}\n\nint main(){\n    fun1(3);\n    cout \u003c\u003c endl;\n    fun2(3);\n}\n```\n\n#### Generalization\n\n- The things that occur before are executed during calling time. We can call it ascending.\n- The things that occur after are executed during returning time. The things that are present with the function also do work during returning time. We can call it descending.\n\n```cpp\nint fun(int num){\n    if(num \u003e 0){\n    cout \u003c\u003c num;\n    cout \u003c\u003c fun(num - 1) * 2;\n    cout \u003c\u003c num;\n    }\n}\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### What is the Difference Between Recursion and Loop?\n\nBoth recursion and loops are used for repeating operations, but they have key differences:\n- **Loops** execute in a straightforward manner, usually iterating **in one direction (ascending order)**.\n- **Recursion** executes **in both ascending and descending order**, making function calls until a base case is met.\n\n| Feature         | Recursion                           | Loop                          |\n|---------------|----------------------------------|------------------------------|\n| **Memory Usage** | High (due to stack frames)       | Low (single iteration variable) |\n| **Execution Speed** | Slower (due to function calls)  | Faster |\n| **Readability** | Easier for complex problems    | Easier for simple problems |\n\n**Recursion:**\n```cpp\nvoid recursiveFunction(int n) {\n    if (n \u003e 0) {\n        cout \u003c\u003c n \u003c\u003c \" \";\n        recursiveFunction(n - 1);\n    }\n}\n\nint main() {\n    recursiveFunction(5); // 5 4 3 2 1\n}\n```\n```\nrecursiveFunction(5)\n├── recursiveFunction(4)\n│   ├── recursiveFunction(3)\n│   │   ├── recursiveFunction(2)\n│   │   │   ├── recursiveFunction(1)\n│   │   │   │   ├── recursiveFunction(0) → Base Case (stops recursion)\n```\n\n**Loop:**\n```cpp\nint main() {\n    for (int i = 5; i \u003e 0; i--) {\n        cout \u003c\u003c i \u003c\u003c \" \"; // 5 4 3 2 1\n    }\n}\n```\n```\ni = 5 → Print 5 → i--\ni = 4 → Print 4 → i--\ni = 3 → Print 3 → i--\ni = 2 → Print 2 → i--\ni = 1 → Print 1 → i--\ni = 0 → Loop stops\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### How Recursion Uses Stack?\n\nEach recursive function call creates an **activation record** in the stack. When the **base case** is reached, the function calls **return in reverse order**.\n\n#### Consider the following recursive function:\n```cpp\nvoid fun(int n) {\n    if (n \u003e 0) {\n        cout \u003c\u003c \"Call: \" \u003c\u003c n \u003c\u003c endl;\n        fun(n - 1);\n        cout \u003c\u003c \"Return: \" \u003c\u003c n \u003c\u003c endl;\n    }\n}\nint main() {\n    fun(3);\n}\n```\n**Function call flow:**\n```\nfun(3)   → Push onto stack\n  fun(2)   → Push onto stack\n    fun(1)   → Push onto stack\n      fun(0)   → Base Case (Stops recursion)\n    (return 1) → Pop from stack\n  (return 2) → Pop from stack\n(return 3) → Pop from stack\n```\n**Stack Memory:**\n```\n| fun(0) |  → Base Case (pops first)\n| fun(1) |\n| fun(2) |\n| fun(3) |  → First pushed, last popped (LIFO)\n```\n\n**[⬆ Back to Top](#table-of-contents)**\n\n---\n\n### What are the Types of Recursion?\n\n- If a recursive function has operations before and after the recursive call, it is called **linear recursion**.\n\n#### **Tail Recursion**\n- A recursive function where the **recursive call is the last statement** in the function.\n- Everything is performed **at calling time**.\n- No operation is left for **returning time**.\n- If additional operations are needed after returning, it is **not tail recursion**.\n- **Easily convertible to a loop.**\n- **Time Complexity:** O(n)\n- **Space Complexity:**\n  - Recursion: O(n) (due to n activation records)\n  - Loop: O(1) (single activation record)\n\n- **Conclusion:** Loops are more efficient for tail recursion.\n\n**Loop:**\n```cpp\nvoid fun(int n){\n    while(n \u003e 0){\n        cout \u003c\u003c n;\n        n--;\n    }\n}\n```\n**Recursion:**\n```cpp\nvoid fun(int n){\n    if(n \u003e 0){\n        cout \u003c\u003c n \u003c\u003c \" \";\n        fun(n - 1);\n    }\n}\nint main(){\n    fun(3);\n}\n```\n**Recursive Call Tree:**\n```\nfun(3)\n|\nfun(2)\n|\nfun(1)\n|\nfun(0) → Base Case (stops recursion)\n```\n**Function call flow:**\n```\nfun(3)   → Push onto stack\n  fun(2)   → Push onto stack\n    fun(1)   → Push onto stack\n      fun(0)   → Base Case (Stops recursion)\n    (return) → Pop from stack\n  (return) → Pop from stack\n(return) → Pop from stack\n```\n**Stack Memory:**\n```\n| fun(0) |  → Base Case (pops first)\n| fun(1) |\n| fun(2) |\n| fun(3) |  → First pushed, last popped (LIFO)\n```\n\n#### **Head Recursion**\n\n- In head recursion, the recursive call is the first statement in the function. No operations are performed before the recursive call.\n\n  - All operations occur **only at returning time**.\n  - **Difficult to convert into a loop** without extra logic.\n\n**Loop:**\n```cpp\nvoid fun(int n){\n  int i = 1;\n  while(i \u003c= n){\n    cout \u003c\u003c n;\n    n--;\n  }\n}\n```\n**Recursion:**\n```cpp\nvoid fun(int n){\n    if(n \u003e 0){\n        fun(n - 1);\n        cout \u003c\u003c n \u003c\u003c \" \";\n    }\n}\nint main(){\n    fun(3);\n}\n```\n**Recursive Call Tree:**\n```\n         fun(3)\n        /\n     fun(2)\n    /\n fun(1)\n /\nfun(0) → Base Case (stops recursion)\n```\n**Function call flow:**\n```\nfun(3)   → Push onto stack\n  fun(2)   → Push onto stack\n    fun(1)   → Push onto stack\n      fun(0)   → Base Case (Stops recursion)\n    (return 1) → Pop from stack → Print 1\n  (return 2) → Pop from stack → Print 2\n(return 3) → Pop from stack → Print 3\n```\n**Stack Memory:**\n```\n| fun(0) |  → Base Case (pops first)\n| fun(1) |\n| fun(2) |\n| fun(3) |  → First pushed, last popped (LIFO)\n```\n\n#### **Tree Recursion**\n\n- If a function calls itself more than once, it is called **tree recursion**.\n- The time complexity of tree recursion is calculated as:\n\n  \\[\n  (2⁰ + 2¹ + 2² + ... + 2ⁿ) = (2ⁿ⁺¹) - 1 \\approx O(2ⁿ)\n  \\]\n\n- The space complexity depends on the height of the recursive tree, which is **O(n)**.\n\n```cpp\nvoid fun(int n)\n{\n   if (n \u003e 0)\n   {\n     printf(\"%d \", n);\n     fun(n - 1);\n     fun(n - 1);\n   }\n}\n```\n**Recursive Call Tree:**\n```\n                fun(3)\n               /      \\\n          fun(2)      fun(2)\n         /     \\      /     \\\n    fun(1)  fun(1) fun(1)  fun(1)\n    /    \\   /   \\  /    \\  /   \\\nfun(0) fun(0) fun(0) fun(0) fun(0) fun(0) fun(0) fun(0) → Base Case (Stops recursion)\n```\n**Function call flow:**\n```\nfun(3)   → Push onto stack\n  fun(2)   → Push onto stack\n    fun(1)   → Push onto stack\n      fun(0)   → Base Case (Stops recursion)\n      fun(0)   → Base Case (Stops recursion)\n    (return) → Pop from stack\n    fun(1)   → Push onto stack\n      fun(0)   → Base Case (Stops recursion)\n      fun(0)   → Base Case (Stops recursion)\n    (return) → Pop from stack\n  (return) → Pop from stack\n  fun(2)   → Push onto stack\n    fun(1)   → Push onto stack\n      fun(0)   → Base Case (Stops recursion)\n      fun(0)   → Base Case (Stops recursion)\n    (return) → Pop from stack\n    fun(1)   → Push onto stack\n      fun(0)   → Base Case (Stops recursion)\n      fun(0)   → Base Case (Stops recursion)\n    (return) → Pop from stack\n  (return) → Pop from stack\n(return) → Pop from stack\n```\n**Stack Memory:**\n```\n| fun(0) |  → Base Case (pops first)\n| fun(1) |\n| fun(2) |\n| fun(3) |  → First pushed, last popped (LIFO)\n```\n\n- **For tree recursion, multiple function calls are pushed onto the stack before returning.**\n\n#### **Indirect recursion**\n\n- **Indirect recursion** occurs when **more than one function** calls one another in a **circular manner**.\n- Instead of a single function calling itself directly, function **A calls B, B calls C, and C calls A** (or any similar cycle).\n\n```cpp\nvoid fun2(int n);\nvoid fun1(int n){\n    if(n \u003e 0){\n        cout \u003c\u003c n \u003c\u003c endl;\n        fun2(n - 1);  // Calling fun2\n    }\n}\nvoid fun2(int n){\n    if(n \u003e 1){\n        cout \u003c\u003c n \u003c\u003c endl;\n        fun1(n / 2);  // Calling fun1\n    }\n}\nint main(){\n    fun1(20);\n}\n```\n**Recursive Call Tree:**\n```\nfun1(20)\n    |\nfun2(19)\n    |\nfun1(9)\n    |\nfun2(8)\n    |\nfun1(4)\n    |\nfun2(3)\n    |\nfun1(1)\n    |\nfun2(0) → Base Case (Stops recursion)\n```\n**Function call flow:**\n```\nfun1(20)  → Push onto stack\n  fun2(19)  → Push onto stack\n    fun1(9)  → Push onto stack\n      fun2(8)  → Push onto stack\n        fun1(4)  → Push onto stack\n          fun2(3)  → Push onto stack\n            fun1(1)  → Push onto stack\n              fun2(0)  → Base Case (Stops recursion)\n            (return) → Pop from stack\n          (return) → Pop from stack\n        (return) → Pop from stack\n      (return) → Pop from stack\n    (return) → Pop from stack\n  (return) → Pop from stack\n(return) → Pop from stack\n```\n**Stack Memory:**\n```\n| fun2(0) |  → Base Case (pops first)\n| fun1(1) |\n| fun2(3) |\n| fun1(4) |\n| fun2(8) |\n| fun1(9) |\n| fun2(19) |\n| fun1(20) |  → First pushed, last popped (LIFO)\n```\n- **For indirect recursion, functions call each other alternately before returning.**\n\n#### **Nested Recursion**\n\n- **Nested recursion** occurs when a recursive function **passes a parameter as a recursive call**.\n- First, it **processes the parameter recursively**, and then the result is used in the main recursion.\n\n```cpp\nint fun(int n){\n  if(n \u003e 100){\n    return n - 10;  // Base condition\n  } else {\n    return fun(fun(n + 11));  // Nested recursion\n  }\n}\nint main() {\n    cout \u003c\u003c fun(95) \u003c\u003c endl;  // Example call\n}\n```\n**Recursive Call Tree:**\n```\n                          fun(95)\n                              |\n               ---------------------------------\n               |                               |\n           fun(fun(106))                   fun(96)\n               |                               |\n       ------------------                ------------------\n       |                |                |                |\n   fun(106)         fun(fun(107))     fun(97)         fun(fun(108))\n       |                |                |                |\n      96       ---------------          97       ------------","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fahadalireach%2Fdsa.concepts.interview.questions","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fahadalireach%2Fdsa.concepts.interview.questions","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fahadalireach%2Fdsa.concepts.interview.questions/lists"}