LeetCode Solutions by Rajput Hemant

website·Indexed 29 days ago

https://rajput-hemant.github.io/leetcode/

A collection of solutions and problem statements for LeetCode challenges, covering a wide range of algorithmic problems such as Reverse Integer, Two City Scheduling, and Design Browser History.

Tokens
56.1K
Snippets
234
Records
261
Agent score
75%

What's inside LeetCode

  1. Determine if two strings are isomorphic

    Two strings s and t are considered isomorphic if the characters in s can be replaced to get t. This requires a consistent one-to-one mapping: all occurrences of a specific character in s must map to the same character in t, and no two distinct characters in s may map to the same character in t. The order of characters must be preserved.

    Example 1: s = "egg", t = "add" -> true Example 2: s = "foo", t = "bar" -> false Example 3: s = "paper", t = "title" -> true

  2. Remove duplicates from a sorted array in-place

    To remove duplicates from an integer array sorted in non-decreasing order, modify the array in-place so that each unique element appears only once in the first k positions. The relative order of elements must be preserved. The function should return the count of unique elements k. This must be achieved with O(1) extra memory without allocating a new array.
    def removeDuplicates(nums: list[int]) -> int:
        k = 0
        for i, item in enumerate(nums):
            if i < len(nums) - 1 and item == nums[i + 1]:
                continue
            nums[k] = item
            k += 1
        return k
    package main
    
    func removeDuplicates(nums []int) int {
    	k := 0
    	for i := 1; i < len(nums); i++ {
    		if nums[i] != nums[k] {
    			k++
    			nums[k] = nums[i]
    		}
    	}
    
    	return k + 1
    }
  3. Solve LeetCode problems using Binary Search

    A curated list of LeetCode problems that can be solved using Binary Search techniques, ranging from Easy to Hard difficulty. Key problems include 'Median of Two Sorted Arrays' (Hard), 'Search a 2D Matrix' (Medium), and 'Binary Search' (Easy).
  4. Find the length of the Longest Palindromic Subsequence

    To find the length of the longest palindromic subsequence in a string s, you can treat the problem as finding the Longest Common Subsequence (LCS) between the original string and its reverse. A subsequence is derived by deleting zero or more elements without changing the order of the remaining elements.

    Constraints:

    • String length: 1 to 1000
    • Characters: Lowercase English letters only.
    public int longestPalindromeSubseq(String s) {
        String str1 = s,
            str2 = new StringBuilder(s).reverse().toString();
        int m = str1.length(),
            n = str2.length();
        int[][] dp = new int[m + 1][n + 1];
        for (int i = 0; i < m + 1; i++)
        for (int j = 0; j < n + 1; j++) {
            if (i == 0 || j == 0)
            dp[i][j] = 0;
            else if (str1.charAt(i - 1) == str2.charAt(j - 1))
            dp[i][j] = 1 + dp[i - 1][j - 1];
            else
            dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
        }
        return dp[m][n];
    }
  5. Convert a sorted array to a height-balanced Binary Search Tree (BST)

    To convert a sorted array into a height-balanced BST, use a recursive divide-and-conquer approach. By selecting the middle element of the current array segment as the root node, you ensure that the number of nodes in the left and right subtrees differs by at most one, maintaining the height-balance property. The process is repeated recursively for the left half (to build the left subtree) and the right half (to build the right subtree).
    package main
    
    // TreeNode defines a binary tree node
    type TreeNode struct {
    	Val   int
    	Left  *TreeNode
    	Right *TreeNode
    }
    
    func sortedArrayToBST(nums []int) *TreeNode {
    	if len(nums) == 0 {
    		return nil
    	}
    
    	return constructBST(nums, 0, len(nums)-1)
    }
    
    func constructBST(nums []int, left, right int) *TreeNode {
    	if left > right {
    		return nil
    	}
    
    	// Choose the middle element as the root to maintain balance
    	mid := (left + right) / 2
    	node := &TreeNode{Val: nums[mid]}
    
    	// Recursively build left and right subtrees
    	node.Left = constructBST(nums, left, mid-1)
    	node.Right = constructBST(nums, mid+1, right)
    
    	return node
    }
  6. Solve the Valid Parentheses problem using a stack

    To determine if a string containing only the characters '(', ')', '{', '}', '[' and ']' is valid, use a stack-based approach. A string is valid if open brackets are closed by the same type of brackets in the correct order, and every closing bracket has a corresponding opening bracket.

    Algorithm:

    1. Iterate through each character in the string.
    2. If the character is an opening bracket ('(', '[', or '{'), push it onto the stack.
    3. If the character is a closing bracket, check if the stack is empty or if the top of the stack is not the matching opening bracket. If either is true, the string is invalid (return false).
    4. After processing all characters, the string is valid only if the stack is empty.
  7. Find the intersection of two integer arrays (Intersection of Two Arrays II)

    Given two integer arrays nums1 and nums2, the goal is to return an array containing their intersection. An element must appear in the result as many times as it appears in both arrays. The result can be returned in any order.

    Constraints:

    • Array lengths: 1 to 1000
    • Element values: 0 to 1000
    Example 1:
    Input: nums1 = [1,2,2,1], nums2 = [2,2]
    Output: [2,2]
    
    Example 2:
    Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
    Output: [4,9]
  8. Convert Celsius to Kelvin and Fahrenheit

    To convert a Celsius temperature to Kelvin and Fahrenheit, use the following formulas:

    • Kelvin = Celsius + 273.15
    • Fahrenheit = Celsius * 1.80 + 32.00

    The input is a non-negative floating point number rounded to two decimal places, and the result should be returned as an array containing [Kelvin, Fahrenheit].

    impl Solution {
        pub fn convert_temperature(celsius: f64) -> Vec<f64> {
            let kelvin = celsius + 273.15;
            let fahrenheit = celsius * 1.8 + 32.0;
            vec![kelvin, fahrenheit]
        }
    }
  9. Find duplicate subtrees in a binary tree using subtree serialization

    To find duplicate subtrees in a binary tree, you can use a recursive traversal to serialize each subtree into a unique string representation. By storing these serializations in a hash map, you can track the frequency of each subtree structure. If a serialization appears for the second time (count equals 1), the corresponding root node is added to the result list. A null node is represented by a special character (e.g., '#') to maintain structural integrity in the serialization.
    package main
    
    import "strconv"
    
    // Definition for a binary tree node.
    type TreeNode struct {
    	Val   int
    	Left  *TreeNode
    	Right *TreeNode
    }
    
    func findDuplicateSubtrees(root *TreeNode) []*TreeNode {
    	// to store the hash value of subtrees
    	hashMap := make(map[string]int)
    	// to store the result
    	res := make([]*TreeNode, 0)
    	// traverse the tree
    	traverse(root, hashMap, &res)
    	return res
    }
    
    // traverse the tree
    func traverse(root *TreeNode, hashMap map[string]int, res *[]*TreeNode) string {
    	// if the root is nil, return "#"
    	if root == nil {
    		return "#"
    	}
    	// traverse the left and right subtree
    	left := traverse(root.Left, hashMap, res)
    	right := traverse(root.Right, hashMap, res)
    	// get the hash value of the subtree
    	subTree := left + "," + right + "," + strconv.Itoa(root.Val)
    	// if the hash value of the subtree is 1, it means that the subtree is duplicated
    	if hashMap[subTree] == 1 {
    		*res = append(*res, root)
    	}
    	// add the hash value of the subtree to the hashMap
    	hashMap[subTree]++
    	return subTree
    }
  10. Solve Jump Game IV using Breadth-First Search (BFS)

    To find the minimum number of steps to reach the last index of an array arr, treat the array as a graph where each index is a node. Edges exist between index i and:

    1. i + 1 (if within bounds)
    2. i - 1 (if within bounds)
    3. Any index j where arr[i] == arr[j]

    Because the goal is the shortest path in an unweighted graph, Breadth-First Search (BFS) is the optimal approach. To optimize the search for indices with the same value, use a hash map to store all indices for each unique value and remove the entry from the map once all indices for that value have been visited to avoid redundant processing.

    use std::collections::{HashMap, VecDeque};
    
    impl Solution {
        pub fn min_jumps(arr: Vec<i32>) -> i32 {
            let mut map = HashMap::new();
    
            // Pre-process: group indices by their values
            for (i, &v) in arr.iter().enumerate() {
                map.entry(v).or_insert(vec![]).push(i);
            }
    
            let mut q = VecDeque::new();
            q.push_back((0, 0_i32)); // (current_index, steps)
    
            let mut visited = vec![false; arr.len()];
            visited[0] = true;
    
            while let Some((i, mut step)) = q.pop_front() {
                if i == arr.len() - 1 {
                    return step;
                }
    
                step += 1;
    
                // Jump to all indices with the same value
                if let Some(v) = map.remove(&arr[i]) {
                    for j in v {
                        if !visited[j] {
                            visited[j] = true;
                            q.push_back((j, step));
                        }
                    }
                }
    
                // Jump to next index
                if i + 1 < arr.len() && !visited[i + 1] {
                    visited[i + 1] = true;
                    q.push_back((i + 1, step));
                }
    
                // Jump to previous index
                if i >= 1 && !visited[i - 1] {
                    visited[i - 1] = true;
                    q.push_back((i - 1, step));
                }
            }
    
            -1
        }
    }
  11. Implement Binary Tree Zigzag Level Order Traversal

    The goal is to return the zigzag level order traversal of a binary tree's nodes' values. The traversal starts from left to right for the first level, then right to left for the next level, alternating directions for each subsequent level.

    Constraints:

    • Number of nodes: 0 to 2000.
    • Node values: -100 to 100.
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Stack;
    import definitions.TreeNode;
    
    public class BinaryTreeZigzagLevelOrderTraversal {
        public static List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> result = new LinkedList<>();
            if (root == null)
                return result;
            Stack<TreeNode> stk1 = new Stack<>(), stk2 = new Stack<>();
            stk1.push(root);
            while (!stk1.isEmpty() || !stk2.isEmpty()) {
                List<Integer> list1 = new LinkedList<>();
                while (!stk1.isEmpty()) {
                    TreeNode currentNode = stk1.pop();
                    list1.add(currentNode.val);
                    if (currentNode.left != null)
                        stk2.push(currentNode.left);
                    if (currentNode.right != null)
                        stk2.push(currentNode.right);
                }
                if (!list1.isEmpty())
                    result.add(list1);
                List<Integer> list2 = new LinkedList<>();
                while (!stk2.isEmpty()) {
                    TreeNode currentNode = stk2.pop();
                    list2.add(currentNode.val);
                    if (currentNode.right != null)
                        stk1.push(currentNode.right);
                    if (currentNode.left != null)
                        stk1.push(currentNode.left);
                }
                if (!list2.isEmpty())
                    result.add(list2);
            }
            return result;
        }
    }