Skip to main content

Posts

Leetcode 83: Remove Duplicates from Sorted List

  1. Problem Statement (Simple Explanation) You’re given the head of a  sorted  singly linked list. You must: Remove  duplicate nodes  so that  each value appears only once . Keep the list sorted. Return the head of the resulting list. Unlike Problem 82, here you  keep one copy  of each value and delete the extra nodes. 2. Examples Example 1: Input: head = [1,1,2] 1 appears twice → keep one. 2 appears once. Output: [1,2] Example 2: Input: head = [1,1,2,3,3] 1 appears twice → keep one. 2 appears once. 3 appears twice → keep one. Output: [1,2,3] 3. Approach – One Pass, O(1) Space The list is sorted, so duplicates are  adjacent . We can scan through the list with a pointer curr: Start curr = head. While curr is not null and curr.next is not null: If curr.val == curr.next.val: We have a duplicate node. Remove it by: curr.next = curr.next.next Do  not  advance...

Chef and String

  Problem Summary You have N students in a row, each either a girl ('x') or a boy ('y'). Students are friends only with their immediate neighbors (left/right). Rules for forming pairs: Each pair must be exactly one boy and one girl. Only  adjacent  students (friends) can form a pair. Each student can be in at most one pair. For each test case (string S of length N), you must find the  maximum number of pairs  that can be formed. Input: T test cases. For each test case: a string S of 'x' and 'y'. Output: For each test case: one integer — the maximum number of valid pairs. Constraints: 1 ≤ T ≤ 100 1 ≤ N ≤ 10 5 Total sum of N over all test cases ≤  3× 10 5 S contains only 'x' and 'y'. Examples Explanation Sample: Input: 3 xy xyxxy yy Output: 1 2 0 Case 1: "xy" Only pair: (1, 2) = 'x' & 'y' → 1 pair. Case 2: "xyxxy" One valid configuration: (1,...

Leetcode 82: Remove Duplicates from Sorted List II

  1. Problem Statement (Simple Explanation) You’re given the head of a  sorted  singly linked list. You must  delete all nodes that have duplicate values , so that only values that appear  exactly once  in the original list remain. Return the head of the resulting list (still sorted). Important: If a value appears more than once,  remove all occurrences  of that value. The list is sorted ascending, so duplicates are in contiguous blocks. 2. Examples Example 1: Input: head = [1,2,3,3,4,4,5] Values: 1 → appears once → keep 2 → appears once → keep 3 → appears twice → remove both 3s 4 → appears twice → remove both 4s 5 → appears once → keep Output: [1,2,5] Example 2: Input: head = [1,1,1,2,3] Values: 1 → appears three times → remove all 1s 2 → keep 3 → keep Output: [2,3] 3. Approach – One Pass with Dummy Head (O(n), O(1)) Because the list is  sorted , duplicates are grouped together. We want t...