Tuesday, October 18, 2022

[LeetCode] Minimum Absolute Difference in BST

Problem: Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.

Example:

Input: root = [4,2,6,1,3]
Output: 1

Input: root = [1,0,48,null,null,12,49]
Output: 1


Approach: A simple inorder traversal is enough to solve this problem as this tree is BST and inorder traversal will output the values in sorted order. Directly look at the implementation to understand the approach better.


Implementation in C#:

    public int GetMinimumDifference(TreeNode root) 

    {

        if (root == null)

        {

            return 0;

        }

        TreeNode prev = null;

        int minDiff = int.MaxValue;

        this.GetMinDiff(root, ref prev, ref minDiff);

        return minDiff;

    }

    

    private void GetMinDiff(TreeNode node, ref TreeNode prev, ref int minDiff)

    {

        if (node == null)

        {

            return;

        }    

        this.GetMinDiff(node.left, ref prev, ref minDiff);

        if (prev != null)

        {

            minDiff = Math.Min(minDiff, Math.Abs(node.val - prev.val));

        }

        prev = node;

        this.GetMinDiff(node.right, ref prev, ref minDiff);

    }


Complexity: O(n)

Monday, October 17, 2022

[LeetCode] Check if the Sentence Is Pangram

Problem: A pangram is a sentence where every letter of the English alphabet appears at least once. Given a string sentence containing only lowercase English letters, return true if sentence is a pangram, or false otherwise.

Example:

Input: sentence = "thequickbrownfoxjumpsoverthelazydog"
Output: true
Explanation: sentence contains at least one of every letter of the English alphabet.
Input: sentence = "leetcode"
Output: false


Approach: We can use HashSet here, basically we will keep adding the characters of the sentence in HashSet. HashSet will ensure the uniqueness. In the end we can check the size of HashSet, if it is 26 then all the letters of english alphabets are present so we can true; false otherwise.

Given its only 26 characters, we can achieve the same thing using an bool array and an int variable. You can understand the approach by just looking at the implementation.


Implementation in C#:

    public bool CheckIfPangram(string sentence)

    {

        bool[] flag = new bool[26];

        int sum = 0;

        foreach (char ch in sentence)

        {

            if (!flag[ch - 'a'])

            {

                flag[ch - 'a'] = true;

                ++sum;

            }

        }        

        return sum == 26;

    }


Complexity: O(n)