




























































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





























































































An array is a fundamental data structure that stores a collection of elements of the same type in contiguous memory locations.
● Indexed Access: Individual elements are accessed using an integer index. In C++, arrays are 0-indexed (indices range from 0 to N - 1 for an array of size N). ● Random Access: Since memory is contiguous, accessing any element given its index takes O(1) constant time. ● Fixed Size: Standard C++ array sizes are fixed upon allocation and cannot grow or shrink dynamically.
#include using namespace std;
int main() { int n; cout << "Enter size of array: "; cin >> n;
// dynamically allocate memory int arr = new int[n];*
// input elements cout << "Enter " << n << " elements:\n"; for (int i = 0; i < n; i++) { cin >> arr[i]; }
// print elements cout << "Array elements: "; for (int i = 0; i < n; i++) { cout << arr[i] << " "; } cout << endl;
// resize array manually (create bigger array) int newSize = n + 2; int newArr = new int[newSize];*
● Dynamic Arrays: Higher-level abstractions (such as std::vector in C++, ArrayList in Java, or standard lists in Python) build upon fixed-size dynamic arrays by automatically reallocating memory when full.
● CPU Cache & Memory Optimization: Because array elements occupy contiguous memory addresses, accessing array data maximizes spatial locality of reference. This allows hardware CPU cache controllers to prefetch adjacent elements into high-speed cache memory, vastly outperforming pointer-based structures like linked lists in sequential access patterns. ● Buffer Allocation in Operating Systems: OS kernels use raw arrays for memory management blocks, I/O buffers, process control table entries, and file descriptor tables. ● Hardware Interfacing and Graphic Buffers: Frame buffers in display adapters store pixel color data in contiguous 2D array blocks to render graphics onto screens smoothly.
● Sorting and Searching Algorithms: Array structure is essential for running efficiently partitioned algorithms such as Binary Search O(log N) access, Quicksort , Mergesort , and Heap Sort. ● Dynamic Programming (DP): DP solutions store intermediate subproblem results in 1D, 2D, or 3D memoization tables (arrays) to convert exponential-time recursive functions into polynomial-time operations. ● Graph Representation: Graphs are often represented as Adjacency Matrices (2D arrays) for fast edge lookups between vertices.
Binary search requires the input array to be strictly sorted. At each step of the algorithm, the middle element is compared to the target. If they do not match, exactly half of the remaining elements are eliminated from the search space.
Mathematically, if you start with n elements, the size of the search area reduces as follows:
● Step 1: n / 2 ● Step 2: n / 4 ● Step k: n / (2^k)
The search ends when the remaining space is reduced to 1 element:
(n / 2^k) = 1 ==> 2^k = n ==> k = log₂ n
This logarithmic growth makes binary search extraordinarily efficient for large datasets. For example, searching through 1 million elements takes a maximum of only 20 comparisons.
● Sorted Array: [2, 5, 8, 12, 16, 23, 38, 56, 72, 91] ,N = 10 ● Target Value: 23
arr[j + 1] = key; } }
/* A utility function to print array of size n */ void printArray( int arr[], int n) { for ( int i = 0; i < n; ++i) cout << arr[i] << " "; cout << endl; }
// Driver method int main() { int arr[] = { 12, 11, 13, 5, 6 }; int n = sizeof (arr) / sizeof (arr[0]);
insertionSort(arr, n); printArray(arr, n);
return 0; }
Two D Array , students, marks of some papers Days, Hours of Study Dynamic two D Array
#include using namespace std ;
class Node { public : int data; Node* next;
Node( int value) { data = value; next = nullptr ;
class SinglyLinkedList { private : Node* head;
public : SinglyLinkedList() { head = nullptr ; }
// Insert at the start void insertAtStart( int value) { Node* newNode = new Node(value);
newNode->next = head; head = newNode;
cout << value << " inserted at start. \n "; }
// Insert at the end void insertAtEnd( int value) { Node* newNode = new Node(value);
if (head == nullptr ) { head = newNode; cout << value << " inserted at end. \n "; return ; }
Node* temp = head;
while (temp->next != nullptr ) { temp = temp->next; }
temp->next = newNode;
cout << value << " inserted at end. \n "; }
// Delete from the start
Node* temp = head; int position = 1 ;
while (temp != nullptr ) { if (temp->data == value) { cout << value << " found at position " << position << ". \n "; return ; }
temp = temp->next; position++; }
cout << value << " not found in the list. \n "; } // Delete a node by its value void deleteNode( int value) {
// Case 1: Empty list if (head == nullptr) { cout << "List is empty.\n"; return ; }
// Case 2: Node to delete is the first node if (head->data == value) { Node* temp = head; head = head->next;
delete temp;
cout << value << " deleted from the list.\n"; return ; }
// Find the node Node* current = head;
while (current->next != nullptr && current->next->data != value) { current = current->next; }
// Node not found if (current->next == nullptr) { cout << value << " not found in the list.\n"; return ;
}
// Node found Node* temp = current->next;
// Skip the node current->next = temp->next;
// Delete the node delete temp;
cout << value << " deleted from the list.\n"; } // Function to print the singly linked list void printList(Node* head) { // Start from the head of the list Node* current = head;
// Run the loop until the current pointer reaches the end (nullptr) while (current != nullptr) { cout << current->data;
// Print a visual arrow if there is another node ahead if (current->next != nullptr) { cout << " -> "; }
// Move the pointer to the next node in the list current = current->next; } cout << endl; }
// Display the list void display() { if (head == nullptr ) { cout << "List is empty. \n "; return ; }
Node* temp = head;
cout << "Linked List: ";
while (temp != nullptr ) { cout << temp->data << " -> "; temp = temp->next;
Fabbonaci Series Palindrome Reverse LL for String Generic LL
Core Variables
● arr[]: The internal array used to store stack elements (fixed capacity or dynamically resized). ● capacity: The maximum number of elements the array can hold. ● top: An integer variable tracking the index of the top element. ○ Initial state: top = -1 (indicates the stack is empty).
Operations & Logic
● Step 1: Check for Overflow : If top == capacity - 1, the stack is full. ● Step 2: Increment top by 1 (top = top + 1). ● Step 3: Assign the new element to arr[top]. ● Time Complexity: O(1)
● Step 1: Check for Underflow : If top == -1, the stack is empty. ● Step 2: Store or return the element at arr[top]. ● Step 3: Decrement top by 1 (top = top - 1). ● Time Complexity: O(1)
● Step 1: Check if top == -1 (Stack Empty). ● Step 2: Return arr[top]. ● Time Complexity: O(1)
Core Concept: Head as the "Top"
In an array, the top is usually at the end. In a linked list, pushing and popping at the tail takes O(N) time (unless maintaining a tail pointer and doubly linked list).
By treating the head pointer as top , every operation happens at index 0:
● Push: Insert a new node at the head O(1). ● Pop: Remove the head node O(1). ● Peek: Return the value inside the head node O(1).
Operations & Logic
1. Push (Insert Element) Adds a new element to the top of the stack.
● Step 1: Create a new node with the given value. ● Step 2: Point the new node's next pointer to the current top. ● Step 3: Update top to point to the new node. ● Time Complexity: O(1).
2. Pop (Remove Element) Removes and returns the top element.
● Step 1: Check for Underflow : If top == null, the stack is empty. ● Step 2: Store the value of top.data (and temporarily store top). ● Step 3: Move top forward: top = top.next. ● Step 4: Return the stored value (and let garbage collection clear the old node). ● Time Complexity: O(1).
3. Peek / Top (View Top Element) Returns the top value without removing the node.
● Step 1: Check if top == null (Stack Empty). ● Step 2: Return top.data. ● Time Complexity: O(1).
why traversal logic has to change to a do-while style: start at head, process it, move to next, and keep going until you arrive back at head — not until you hit null.
#include using namespace std;
// Node structure for the circular linked list struct Node { int data; Node* next;
Node(int value) { data = value; next = nullptr; } };
class CircularLinkedList { private: Node* head; Node* tail;
public: CircularLinkedList() { head = nullptr; tail = nullptr; }
~CircularLinkedList() { if (!head) return; Node* current = head; do { Node* temp = current; current = current->next; delete temp; } while (current != head); }
bool isEmpty() { return head == nullptr; }
// Insert a node at the end of the list void insertEnd(int value) { Node* newNode = new Node(value); if (isEmpty()) { head = newNode; tail = newNode; newNode->next = head; // points to itself } else { tail->next = newNode; tail = newNode; tail->next = head; // maintain circular link } }
// Insert a node at the beginning of the list void insertBeginning(int value) { Node* newNode = new Node(value); if (isEmpty()) { head = newNode; tail = newNode; newNode->next = head; } else { newNode->next = head; head = newNode; tail->next = head; // maintain circular link } }
// Insert a node at a specific position (0-indexed) void insertAtPosition(int value, int position) { if (position <= 0 || isEmpty()) { insertBeginning(value); return; }
Node* current = head; for (int i = 0; i < position - 1; i++) { current = current->next; if (current == head) break; // avoid overshooting past tail }
if (current == tail) { insertEnd(value); return;
} while (current != head);
cout << "Value " << value << " not found in the list." << endl; }
// Search for a value; returns true if found bool search(int value) { if (isEmpty()) return false; Node* current = head; do { if (current->data == value) return true; current = current->next; } while (current != head); return false; }
// Display the list once (single traversal) void display() { if (isEmpty()) { cout << "List is empty." << endl; return; } Node* current = head; do { cout << current->data << " -> "; current = current->next; } while (current != head); cout << "(back to head: " << head->data << ")" << endl; }
// Count number of nodes int size() { if (isEmpty()) return 0; int count = 0; Node* current = head; do { count++; current = current->next; } while (current != head); return count; } };
int main() { CircularLinkedList list;
// Insert elements list.insertEnd(10); list.insertEnd(20); list.insertEnd(30); list.insertBeginning(5); list.insertAtPosition(15, 2);
cout << "List after insertions: " << endl; list.display();
cout << "\nSize of list: " << list.size() << endl;
cout << "\nSearching for 20: " << (list.search(20)? "Found" : "Not Found") << endl; cout << "Searching for 99: " << (list.search(99)? "Found" : "Not Found") << endl;
cout << "\nDeleting value 20..." << endl; list.deleteValue(20); list.display();
cout << "\nDeleting head value 5..." << endl; list.deleteValue(5); list.display();
cout << "\nDisplaying list looped twice around the circle: " << endl; list.displayLoop(2);
return 0; }
Each node in a doubly linked list includes:
● Data: The actual information held within the node, which could be numbers, strings, or any other data type.