Docsity

MASTER DSA NOTES FOR PLACEMENTS, Lecture notes of Programming Languages

Partial preview of the text

Download MASTER DSA NOTES FOR PLACEMENTS and more Lecture notes Programming Languages in PDF only on Docsity!

| DSA _ REVISION SHEET @aman_views a = Page 3/30 _ IMPORTANT. ARRAY PATTERNS ws: re Ted Pointers fare ss Peo eee ° Useful for pr problems like pair sum, fing pairs, partitioning, Jt ae e For sorted array pair sum: _ lites - Initialize left = 0, right = n- rh, eT ie re - If sum < target — move left++ (to increase sum). | 1 aN a | 6 8 | 10 | - If sum > target — move right-- (to decrease sum). 4 t - If sum == target — pair found. left right 2.| Sliding Window. e Useful for problems on contiguous subarrays (fixed size or narabley! 3 e Fixed size window sum (size = k): ee - Compute sum of first k elements. of att a{2] gl a(4] | [5] - Slide the window using: sum += ali] - ali-k] window (size k) 1 - This removes the element going out and adds the new element. e Time Complexity: O(n) 3.| Prefix Sum © prefix[i] stores the aim a elements from index 20. 10 | Ga seXOMDIC - mann e Formula: prefix[i] = prefix[i-1] + ali] ee 4 = 38. with prefix[0] = a[0] ion ee da e Range sum (l to oe upretix = 2,6, 7, 10 ] rangeSum(l, r) = prefix Er] -(1>0? prefix [l- 1]: 0) e This answers range sum queries in O(1) after precomputation. — 4. Kadane’s Algorithm e Finds the maximum sum of a contiquous subarray. e Idea: at each index, either start a new subarray from ali] or extend the current subarray. e Code (Java): Ra. Maximum subarray sum int curr = a[0]; in O(n) time and int best = al0]; pe et 7 —O(1) space. for (int i= re itt) { —- ———— curr = Math.max(al[i], curr + ali]);— = best = Math.max (best, curr); — ee tee ae | aa . gh 3 | Paie/ partition — Two pointers | Contiguous range -> Window/Prefix | Max subarray > Kadane | DSA REVISION SHEET @aman_views | pea 5 ___ Page 1/30 __| —_——FIME_& SPACE _COMPLEXITy —___- Big-O, Q and ©: e Big-O (0) -> upper bound / worst-case growth. e Omega (Q) = lower bound / best-case growth. e Theta (0) -— tight bound (both upper and lower bound). Common Growth Order : Dy O(1) < O(logn) < O(n) < O(nlogn) < O(n?) < O(2") < O(n!) = eee —__—_—— > increasing or order OF mgrowth) amen aes, oa Quick Loop Rules : [+ Array element access: int x = arr[0]} | => 0(1) e Single loop (n iterations): for (int i = 0; i O(n?) for (int j= 0; j O(logn) he constant work : aS Eon Space “Complexity : oe e Total space = Input space + Auxiliary space (extra space used by algorithm). e Variables (int, char, etc.) use constant space > O(1). e Array allocation : intl] arr = new int[n]; > O(n). © Recursion: if recursion depth is n (and each call uses constant space), then space complexity is —> O(n). . | Golden Rule : e Drop constants and lower-order terms while finding complexity . ¢ Examples: okey = O(n) eee [ Meas Measure growth as input n becomes large. | DSA REVISION SHEET @aman_views MERGE SORT & QUICK SORT Page 6/30 _ Merge Sort Idea_ i e ® Divide the array into two halves. e Recursively sort both halves. e Merge the two sorted halves. Working (Example) : Sort the array: [8, 3, 2, 6] 8) 3 2061 x mS : 8% 3) [2, 6] gee BS le 3 [3] [3] [2] [6] J i i V merge > |[3, 8] merge > |[2, 6] “= A merge > [2, 3, 6, 8] Algorithm (Java) : void mergeSort(int[] a, int |, int r) { if (l 4 (smaller) Pivot Carger) a 2.3. Lomuto Partition (Java) : Gees int partition(int[] a, int low, int high) (os int pivot = a(high]; int t = low - 4; for (int j = low; j < high; peo Ls if (alj] A= pivot) if a a “i++; int temp = afi}; ali] = a[j]; — _ a[j] = temp; y ‘int temp = afi + 1]; ali + {] = a[high]; ~~ a[high] = temp; return i+ 4; xe Quick Sort (Java) : void quickSort(int[] a, “int low, int high) iT if (low < high) { - See int, pi partition(a, low, u, high); quickSort(a, low, pi-1); _ quickSort(a, pi+41, high); // pivot index — = Complexity & Properties : Average Time Complexity: O(n log n) — ° Worst Case Time Complexity : O(n). _© Space Complexity : O(log n) (recursion stack) | @ Stable : No © In-place : Yes (uses constant extra space) Campanicon / When ton Use : | e Guaranteed performance / stability —» Merge Sort. (O(n log n), stable) ¢ Low extra memory / fast average —> Quick Sort (in- -place, O(n log n) average) DSA REVISION SHEET @aman-_views } - = = a{j+1] = key; ; : —* } } 4.| Quick Comparison (When to Use) : Nearly sorted data Few swaps / minimal changes Learning / simple implementation 43 Page_ 5/30 BASIC SORTING ALGORITHMS Bubble Sort : nid, ; aaa boreal © Repeatedly swap adjacent elements if a[j] > alj+1]. « Largest element moves to the end in each pass. * One pass example: [5,2,4] —> [2,4, 5] public static void bubbleSort Cint[] a) { int n = a.length; for (int i= 0; i a[j +1]) { 3 orst Case O(n ) ye Oil : aljl; Stable Yes a{j] = aj +1); = alj+1] = temp; In-place Yes ; swapped = true; } if (!swapped) break; // already sorted } , ak ee Selection Sort : - ae e Find the minimum element from unsorted part and place it at index i. e After each pass, the first i elements are in sorted order. public static void selectionSort(int[] a) { int n = a.length; ' = ip for (int i = 8; i-= 0 && a[j] > key) { te Si alj+1] = alj]; Stable Yes ech In-place Yes — Insertion Sort — Selection Sort — Bubble Sort DSA REVISION SHEET @aman_views $$ —_—__—_— "RECURSION & BACKTRACKING z Recursion Basics Idea : e A function calls itself to solve a problem. e Must have a base case to stop. e Recursive case solves a smaller subproblem. Example (Factorial) : nt = nx (n= 1)! ee) static int fact(int n) { if (n <= 1) return 1; // base case . return n * fact(n-1); // recursive case } Call Stack (fact (4)) : fact(4) | = 4 x fact(3) Peturns (2 2. rash ee ey ; tr “- => 3x fact(2) turk 6 fact(2) | — 2 x fact(1) =e J returns 24 fact(1) | > returns 1 (base case) (n recursive calls) (call stack space) Complexity : . O(n) e Space Complexity : O(n) e Time Complexity : Subset Pattern Idea : e For each element , we have two choices : Include the element in current subset. e Exclude the element from current subset. Example : Generate all = of [1, 2] Exclude =e = lude 1 ” | To | my i Exclude 2 _ a pe | = al ep) eu © This naturally forms a decision tree using recursion. Steps to solve using recursion : © Trust the recursive result to build the answer. oe e Recursive case : ° 3. Backtracking ss Recursion Checklist Define the state /parameters for the function. _ e Write the stopping condition (base case). e Solve one smaller subproblem (recursive case). Example Checklist for factorial : State : n (integer) Base case: if n <= 14 return 1 ' return n * fact(n - 1) factorial of (n - ia Smaller subproblem : Tdea : ¢ Recursion that chooses, explores, “and then undoes a choice (backtracks). ¢ Systematically tries all possibilities. ¢ Used to find all valid solutions under constraints. . Template (Java): — void solve (State s) { if (isGoal(s)) { save (s); return; for (Choice c : choices(s)) { a apply (ce); //_ make a choice solve (nextState); // explore 7 —undo(c); —//_ backtrack “(undo c choice) 5. Remember 5.1 Key Points : ee 2 _@ Recursion explores the space of calls. e Backtracking restores the state after exploring a choice. , © «Use backtracking when you need to try multiple possibilities and undo changes. 5.2 Common Uses : © Generate all subsets of a set, Generate all permutations. e _@ N-Queens problem. e ° Maze / grid path finding (all paths). Solving constraint satisfaction problems. DSA_REVISION SHEET @aman_views | ae faa ee 4 7/30 “STRINGS IN JAVA a Create & Access : iene seas String 6 2=" [GMa ; 0s ane 1 create a strin oe, nA int_n = Ss. length(); // \ength of string (4) qi char ch = s.charAt(i); // character at index i ar String sub = s. substring (1, r); // substring from index | (inclusive) to r (exclusive) String is immutable. i Le ee eee i Compare Correctly : Rie iirg 35. ee SS ee e si.equals(s2) Compares content of two strings. lize dh “4 e si. compareTo(s2) gives lexicographic order (negative, zero or positive). e Do not use == for content comparison. aSraa “5 ! Important. Methods : ees feed SET ae E e s.toLowerCase() = ‘returns SUING IN SLOWEY COE , simennnsna sean nnunn og e s.toUpperCase() — returns string in in uppercase. y2 z e s.contains("a") — checks if substring exists — (returns boolean). aad ° s. indexOf("a" = returns first ir index (or -1 if not found), ° s.replace("a", uy) — returns a new “string with replacements. _ Lone f ® s.split(", ZN) as sp lits string into array of substrings. SE ae) > removes leading and trailing spaces. Palindrome : aed Sige. Check if a string is palindrome using. two pointers. ‘static boolean isPalindrome(String s) { Time Complexity : O(n) his int L = 0, r = gs. length() -1; ale a nye g Mh ae “Complexity 0(4) ns if (s.charAt(|) != s.charAt(r)) return false; _| Compares characters from t+ both ends moving — towards — sa eo - the center. Fe return true; a — ie Anagram : = Two strings are anagrams if they have the same characters with the same Frequency. 5 static boolean “isAnagrams (String 1, String $2) { | Tirne Complexity : O(n) if (si. length() != s2.length()) return alse: 5 ue BC intl] freq = new int 260, pace Complexity : O(1) _ for (int i = 0; i < st.length(); i++) freq[st.charAt(i) - ‘a']++; Increment frequency OY oa for (int i = 0; i < $2. length(); i++) sede. charAt(i) - ‘a']--; first string, decrement for (int x : freq) if (x ae 0) return false; for second string. ; return true; All zeros means anagram. StringBuilder : Rese Se = StringBuilder sb = new StringBuilder (); e Use StringBuilder for frequent sb. append (“aman”) ; // appends at end modifications (mutable). 7 sb. insert (0, "Hi "); // inserts at index ¢ Repeated concatenation: = sb. deleteCharAt(2) ; // deletes character at index String : O(n?) perigek = | sb. reverse(); // reverses the string ; ; ; String res = sb.toString(); // converts to String StringBuilder : O(n) saa Immutability — String | Frequent modification + StringBuilder DSA REVISION SHEET @aman_views IMPORTANT LINKED LIST ALGORITHMS Reverse AE pam & _ Page 11/30 Reverse a singly linked list using three. pointers. Original : ListNode prev = null; [10 | lop i300 > nulls ListNode cur = head; while (cur != null) { | Reverse ListNode next = cur.next; // store next node =e i: cur.next = prev; // reverse the link — After Reverse : — prev = cur; // move prev forward 30 L-sl 20 ke 10 | =s"null cur = next; // move cur forward } Time Complexity : O(n) head = prev; // new head Space Complexity : O(1) Find Middle : Use two pointers (slow and fast). Slow moves 1 step and fast moves ih steps. When fast reaches end, slow will be at the middle node. ListNode slow = head; Time Complexity : O(n) ListNode fast = head; ; Space Complexity : O(1) while (fast != null && fast.next != null) { i; slow = slow.next; // move 1 step Example 3 = fast = fast.next.next; // move 2 steps 10 31.20 30 } return slow; // middle node Middle (slow) — Nth Node from End : Move fast pointer n steps ahead, then move both slow and fast together until fast reaches end. Slow will be at the nth node from the end. eet an head; — 7 Time Complexity : O(n) or (int | = Of; h< nj itt : a ne if (fast == null) return null; // n > length _ space Complexity O(1) fast = fast.next; } = a —— ListNode slow = head; Example: (n=2) | 7 : ‘ while (fast != null) { Tot ee oo wl elesd Ls nat aoe slow = slow.next; fast = fast.next; 2nd from end return slow; __// nth node from end _ 7 Detect Cycle — Floyd’s Tortoise and Hare : “Use two pointers. Slow moves 1 step and fast moves 2 steps. If they ever meet, a cycle exists in the linked list. | Time Complexity : O(n) ‘Space Complexity 0(1) ListNode slow = head; eS ListNode fast = head; Fvample (GEOR while (fast != null && fast.next != null) f{ slow = slow.next; 1 a eee ae eae fast = fast.next.next; _ if (slow == fast) return true; // cycle detected aA } cycle —— +— return false; : — //-no-cy le —— Ee Pattern / | Key Takeaway : ; | e Reverse —> 3 pointers | © Middle / Cycle — slow & fast | e Nth from end — fixed gap DSA ia At Oe SHEET @aman_views SINGLY LINKED LIST. aeuaeriai: Node Structure : e Each node stores data and a reference © data can be of any type (int, String, ae). to the next node. e next stores the address of the next node. e The last node points to null. e If next = null, it is the last node. class Node { e Nodes are created using new keyword. int data; Node next; Node(int data) { this.data = data; } } = Create & Link: e Create nodes and link them using next. HEAD = e head stores the reference to the first node. if Node head = new Node(10); ES ar head.next = new Node(20); 10 |-¢ Z0 Fine a 30 | null | . head.next.next = new Node(30); Traverse : e Start from head and move to next node until null. © Time Complexity : O(n) e Visit each node (e. g., print its data). ¢ Space Complexity : O(1) for (Node cur = head; cur != null; cur = cur.next) { e Visits all nodes from head System. out.print(cur.data + " "); to end in order. } fs : ee Insert : et iy e Insert at Beginning : e Insert at End : e Create new node, set its next to current e Create new node and move to the last node head and update head. whose next is null, then link it. Node n = new Node(x); Node n = new Node(x); n.next = head; if (head == null) { head = n; head = n; ==: } else { = Delete by Value : Node tail = head; e Handle case when head itself has the value. while (tail.next iE null) { e Otherwise, stop at the previous node and Paul tail next link it to the next of current node. } i te boolean delete(int key) { } a eae if (head == null) ier false; =— if (head.data == key) { // delete head e Returns true if a node with given value head = head.next; is deleted, else false. return true; e Deletes only the first occurrence. Node cur = head; 6. Complexity : while (cur.next ! = null && cur.next.data != key) { cur = cur.next; Access / Search : O(n) (need to traverse nodes) "i Insert at head : O(1) Delete at head : O(1) j Insert at end : O(n) (traverse to last node) return true; i ‘Delete at end : O(n) (traverse to second last node) } — ih Insert at end : O(1) (if we maintain a tail pointer) if (cur.next == null) return false; // not found cur.next = cur.next.next; DSA REVISION SHEET @amoan_views STACK | eel LIFO Principle : PUSH POP (add at top) (remove from top) e Last In, First Out. e Insertion and deletion happen only at the top. Page ‘2/30 _ e The most recently added element is the first one to be removed. 10 Stack Array Implementation : class ArrayStack { intl] a; int top = -1; ArrayStack (int n) {- ‘ a = new int[n]; void push(int x) { _— if (top == a.length -1) { throw new RuntimeException ("Overflow") ; al++top] = x; int pop() { if (top == -1) { throw new RuntimeException("Underflow”) ; return a[top--]; } int peek() { return a[top]; boolean isEmpty() { : return top == -l, } Recommended Java Usage : 4. Complexity e push() : O(1) @ pop() : 0(1) e peek() : O(1) e Space : O(n) Deque st = new ArrayDeque<>(); (for n elements) st. push(10); 5. Applications : st. push(20) ; Function calls (call stack / recursion). int x = st.peek(); // returns 20 Undo / Redo operations (e.y., text editor). int y = st.pop(); // returns 20 Expression evaluation (infix, postfix, prefix). a ee : Depth First Search (DFS) in graphs. boolean empty st. isEmpty Q; // false Balanced. parentheses / brackets checking. Monotonic stack (useful in many problems). e Prefer Deque over legacy Stack. e Use ArrayDeque which is faster and recommended. e Provides push(), pop(), peek(), isEmpty() operations. ®ees#ee DSA REVISION SHEET @amoan_views ____ Page 14/30 _ QUEUE _& DEQUE Queue_— FIFO : * First In, First Out (FIFO). e Elements are inserted ot the rear and removed from the front, | e It follows the order of arrival. e Used when we need to process elements | in the same order as they come. <— REAR FRONT—>| 10 20 | 30 Operations : e offer() / enqueue() — insert element at rear, e poll() / dequeue() — remove element from front. e peek() — return front element (without removing). Java Queue : Queue q = new ArrayDeque<>(); Common Operations (All _O(1)) : q.offer(10); e offer(e) —> insert at rear q.offer(20); e poll() —> remove from front Integer front = q.peek(); // returns 10 e peek() > get front element Integer x = q.poll(); // removes and returns 10 | © isEmpty() —> check if empty boolean empty = q.isEmpty(); ° size() | — > number of elements | Circular Queue : e Use an array with front, rear, size and capacity. e The rear and front move in a circular manner using modulo operation. Enqueue : rear = (rear + 1) % capacity Dequeue : front = (front + 1) % capacity Queue is full when size capacity. Queue is empty when size == capacity = 5 i front 0 (after wrap-around) Deque : e Double-ended queue. Common Operations: —_ e Elements can be inserted and removed from both ends e addFirst(e) — ‘insert at front (front and rear). e addlast(e) -> insert at rear e Supports all queue operations and also operations * removeFirst() —> remove from front at the front. e removeLast() —> remove from rear e Can work as both queue and stack. © peekFirst() > get front element Java Deque : | © peeklast() — get rear element Deque dq = new ArrayDeque<>(); Compleity (All o(1)): dg .addFirst(10) ; // insert 10 at front addFirst(e) = dq.addLast (20); // insert 20 at rear e addLast(e) dq. peekFirst (); // returns 10 ® removeFirst () dq. peekLast(); /] returns 20 © removeLast() $8 §§ dq. removeFirst () ; // removes 10 im peekFirst() Lar dq. removeLast() ; // removes 20 e peekLast ( ) Z Uses : ¢ Breadth First Search (BFS) in graphs (standard queue). CPU / process scheduling (ready queue). aL 3 - ~—- Buffering (e.g. 10 buffers, streaming data). —. Sliding window maximum / minimum (usually using deque). oo Can be used as a stack replacement (using deque). — Core Idea : DSA REVISION SHEET @aman_views HASHING —> HASHMAP. & HASHSET Hash function maps a key to a bucket (index) in an array. ¢ Collision : When multiple keys map to the same bucket. e Java handles collisions using chaining (linked list / balanced tree in some cases). e Average time for insert, search, delete : O(1) Worst case time complexity : O(n) (when many keys collide). Key (k) --—>} hash(k) -—> ee ae 4 : 2 3 a mane. : y Y t i 30 21 42 . ¥ v - Java ‘Syntax : Freq uency Map : HashMap (stores key-value pairs) Map map = new HashMap<>(); map. put(k, v); /I insert or update map. get(k); // returns value (or null) map. getOrDefault(k, 0); // value or default map.containsKey(k); // check if key exists map. remove(k); // remove key (and value) HashSet (stores unique keys) Set set = new HashSet<>(); set.add(x); // insert (if not present) | set.contains(x); // check if exists set remove(x); // remove key Count frequency of elements using HashMap. For each element x, increment its count. Map map = new HashMap<>(); for (int x : a) { : map.put(x, map.getOrDefault(x, 0) + 1); } Example : fe2)| Array : (2,4, 2,3, 1,2] —> |2=3_ Spe al 4. | 5. 6. Two Sum : : Given an array, find indices of two numbers that sum to target. Use a HashMap to store number — index. For each element, check if (target - ali]) exists in the map. If yes, return the indices. One pass solution : O(n) time, O(n) space. intl] twoSum(int[] a, int famset) { _ Page 15/30 Map(); for (int i = 0; i < a.length; i++) { int need = target - ali]; if (map.containsKey(need)) { return new int[]{map.get(need), i}; } map.put(aLi], i); // store current index _ . Miele return new int[]{}; // if no pair found } Prefix Sum + HashMap: | e Find if there exists a subarray with sum k. ¢ Maintain prefix sum and check if (prefix - k) exists in the map. If yes, a subarray with sum k exists. e Store the earliest index of each prefix sum. e Time Complexity : O(n) | “Space Complexity : boolean hasSubarraySum(int[] a, int k) { Map map = new AEE map.put(0, -1); // prefix sum 0 at index - int prefix = 0; for (int i = 0; i < a.length; i++) { prefix += ali]; =: ws if (map.containsKey (prefix - k)) { return true; // subarray found if (!map.containsKey(prefix)) { map. put(prefix, i); return false; } O(n) // store earliest index Remember : HashMap stores key-value pairs (keys. are “ unique). HashSet stores unique keys (no values). Both are based on hashing and provide average O(1) time for insert, search and delete. If using custom objects as keys (e. g., class), override equals() and hashCode () methods correctly. DSA REVISION SHEET @aman_views TREE _TRAVERSALS = Page 17/30 _ DFS Traversals : Depth First Search (DFS) visits nodes by going as deep as possible. Three types : All can be implemented using recursion (or stack). Preorder Traversal : Preorder, Inorder, Postorder. Inorder Traversal : Example Tree : | Postorder Traversal : Order : Order : Root, Left, Right Output : 12 4 5 3 Java : void preorder(Node n) { if (n == null) return; visit(n) ; preorder (n.left) ; preorder (n. right); } } Level Order — BFS: Breadth First Search (BFS) visits nodes level by level using a queue. Start from root, push it to queue. Process nodes in FIFO order and push their children (left to right). Java : Queue q = new ArrayDeque<>(); q. offer (root) ; while ('q.isEmpty()) { TreeNode n = q.poll(); visit (n) ; if (n.left != null) q.offer(n.left); if (n.right != null) q.offer(n.right); Complexity : Java: if (n e Level Order (BFS) uses a queue. Left, e Output: 42513 void inorder(Node n) { null) return; inorder(n.left); visit (n) ; inorder(n.right) ; All traversals (Preorder, Inorder, Postorder, Level Order) visit each node once. | e Recursive DFS (Preorder / Inorder / Postorder) uses call stack. Root, Right Order : Left, Right, Root Output: 45231 Java: void postorder(Node n) { if (n == null) return; postorder (n.left); postorder (n.right) ; visit (n); } Traversal Order (using example tree) : > 1 5 2 o[ 3 | >| 4 OUCpUL 7 wee M2 wero ee me Space Complexity : O(h) (h = height of tree) Space Complexity : O(w) (w = maximum width of tree) e Pre = root first Remember : | e In = root middle a=] | e Post = root last. DSA REVISION SHEET @aman_views ——— r ___ Page 18/30. IMPORTANT BINARY TREE PROBLEMS — Height : e Height of a binary tree is the number of nodes on the longest path from root to a leaf (i.e. maximum depth). e Height of empty tree = 0. e Computed using recursion. Java : int height(Node n) { if (n == null) return 0; return 1 + Math.max(height(n.left), } height(n.right)); Size : e Size of a binary tree is the total number of nodes in the tree. e Size of empty tree = 0. Java : int size(Node n) { e Time Complexity : O(n) (visit each node once) e Auxiliary Space : O(h) (recursive stack, h = height) Longest root-to-leaf Doth ate 5 Oc | we Height = 4 nodes © Time Complexity : O(n) e Space Complexity : O(h) (recursion stack) return (n == null) ? 0: 1 + size(n.left) + size(n.right); } Diameter : e Longest path between any two nodes in a tree. e At a node, diameter can pass through it and has length = leftHeight + rightHeight. Use a global variable to maintain maximum value. Optimized solution : Single DFS, O(n). Here, diameter is measured in number of EDGES (not nodes). Balanced Tree : e A binary tree is height-balanced if for every node, |leftHeight - rightHeight| < 1. e Optimized method : return height if balanced, otherwise return -1. e If any subtree is unbalanced, propagate -1. Lowest Common Ancestor : e Find LCA of two nodes p and q in a general binary tree (not necessarily BST). e If root is null or matches p/q, return root, e If both left and right calls return non-null, current node is LCA. Views : © Left View : first node at each level (BFS). e Right View : last node at each level (BFS). e Top View : use horizontal distance (HD) and BFS. e Bottom View: use horizontal distance (HD) and BFS (store last node for each HD). Java : Java (optimized) : int diameter(Node n) { int(] ans = new int{1]; // global max heightForDiameter(n, ans); return ans[0]; // diameter in edges heightForDiameter(Node n, intl] ans) { if hn == null) return 0; int lh = heightForDiameter(n.left, ans); int rh = heightForDiameter(n.right, ans); | ans[0] = Math.max(ans[0], th + rh); } return 1 + Math.max(th, rh); 7 Java : int check(Node n) { if (n == null) return 0; _ = int th = check(n.left); if (th == -1) return -1; int rh = check(n.right); if (rh == -1) return -1; if (Math.abs(th-rh) > 1) return -1; : return 1 + Math.max(lh, rh); int } Boolean isBalanced(Node root) { return check(root) != -1; } Time: O(n) Space : O(h) Node lca(Node root, Node p, Node q) { if (root == null || root == p || root == q) return root; Node left = lca(root.left, p, q); Node right = lca(root.right, p, q); - if (left != null && right != null) return root; et l= ? : ri a } return (left != null) ? left : right; Time: O(n) Space ;.0(h) Example Tree : ,Miews: Jo Left View :[1, 2, 4] © Right View : [1, 3, 7] © Top View :[4, 2,1, 3, 7] © Bottom View: [4, 5, 6, 3, 7]