K-th Smallest Prime Fraction

You are given a sorted integer array arr containing 1 and prime numbers, where all the integers of arr are unique. You are also given an integer k.

For every i and j where 0 <= i < j < arr.length, we consider the fraction arr[i] / arr[j].

Return the kth smallest fraction considered. Return your answer as an array of integers of size 2, where answer[0] == arr[i] and answer[1] == arr[j].

Example 1:

Input: arr = [1,2,3,5], k = 3
Output: [2,5]
Explanation: The fractions to be considered in sorted order are:
1/5, 1/3, 2/5, 1/2, 3/5, and 2/3.
The third fraction is 2/5.

Example 2:

Input: arr = [1,7], k = 1
Output: [1,7]

Constraints:

  • 2 <= arr.length <= 1000
  • 1 <= arr[i] <= 3 * 104
  • arr[0] == 1
  • arr[i] is a prime number for i > 0.
  • All the numbers of arr are unique and sorted in strictly increasing order.
  • 1 <= k <= arr.length * (arr.length - 1) / 2
public class Solution {
    public int[] KthSmallestPrimeFraction(int[] arr, int k) {
        var dict = new SortedDictionary<double, int[]>();
        for(int i = 0; i < arr.Length; i++)
        {
            for(int j = i+1; j < arr.Length; j++)
            {
                var key = (double)arr[i]/arr[j];
                var value = new int[]{arr[i], arr[j]};
                dict.Add(key, value);
            }
        }

        int count = 1;
        foreach(var item in dict)
        {
            if(count == k)
            {
                return item.Value;
            }

            count++;
        }

        return null;
    }
}

Relative Ranks

You are given an integer array score of size n, where score[i] is the score of the ith athlete in a competition. All the scores are guaranteed to be unique.

The athletes are placed based on their scores, where the 1st place athlete has the highest score, the 2nd place athlete has the 2nd highest score, and so on. The placement of each athlete determines their rank:

  • The 1st place athlete’s rank is "Gold Medal".
  • The 2nd place athlete’s rank is "Silver Medal".
  • The 3rd place athlete’s rank is "Bronze Medal".
  • For the 4th place to the nth place athlete, their rank is their placement number (i.e., the xth place athlete’s rank is "x").

Return an array answer of size n where answer[i] is the rank of the ith athlete.

Example 1:

Input: score = [5,4,3,2,1]
Output: ["Gold Medal","Silver Medal","Bronze Medal","4","5"]
Explanation: The placements are [1st, 2nd, 3rd, 4th, 5th].

Example 2:

Input: score = [10,3,8,9,4]
Output: ["Gold Medal","5","Bronze Medal","Silver Medal","4"]
Explanation: The placements are [1st, 5th, 3rd, 2nd, 4th].

Constraints:

  • n == score.length
  • 1 <= n <= 104
  • 0 <= score[i] <= 106
  • All the values in score are unique.
public class Solution {
    class DescendingComparer<T> : IComparer<T> where T : IComparable<T> 
    {
        public int Compare(T x, T y) 
        {
            return y.CompareTo(x);
        }
    }

    public string[] FindRelativeRanks(int[] scores) {
        var dict = new SortedDictionary<int, int>(new DescendingComparer<int>());
        var n = scores.Length;
        var result = new String[n];
        var count = 1;
        for(int i = 0; i < n; i++)
        {
            dict.Add(scores[i], i);
        }

        foreach(var item in dict)
        {
            if(count == 1)
            {
                result[item.Value] = "Gold Medal";
            }
            else if(count == 2)
            {
                result[item.Value] = "Silver Medal";
            }
            else if(count == 3)
            {
                result[item.Value] = "Bronze Medal";
            }
            else
            {
                result[item.Value] = count.ToString();
            }

            count++;
        }

        return result;
    }
}

Double a Number Represented as a Linked List

You are given the head of a non-empty linked list representing a non-negative integer without leading zeroes.

Return the head of the linked list after doubling it.

Example 1:

Input: head = [1,8,9]
Output: [3,7,8]
Explanation: The figure above corresponds to the given linked list which represents the number 189. Hence, the returned linked list represents the number 189 * 2 = 378.

Example 2:

Input: head = [9,9,9]
Output: [1,9,9,8]
Explanation: The figure above corresponds to the given linked list which represents the number 999. Hence, the returned linked list represents the number 999 * 2 = 1998.

Constraints:

  • The number of nodes in the list is in the range [1, 104]
  • 0 <= Node.val <= 9
  • The input is generated such that the list represents a number that does not have leading zeros, except the number 0 itself.
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int val=0, ListNode next=null) {
 *         this.val = val;
 *         this.next = next;
 *     }
 * }
 */
    public class Solution
    {
        public ListNode DoubleIt(ListNode head)
        {
            if (head == null)
            {
                return head;
            }

            var number = new List<int>();
            while (head != null)
            {
                number.Add(head.val);
                head = head.next;
            }

            var carry = 0;
            for (int i = number.Count - 1; i >= 0; i--)
            {
                var doubleNum = number[i] + number[i] + carry;
                number[i] = doubleNum % 10;
                carry = doubleNum / 10;
            }

            if (carry > 0)
            {
                number.Insert(0, carry);
            }

            var temp = new ListNode();
            head = temp;
            for(int i = 0; i < number.Count; i++)
            {
                temp.next = new ListNode(number[i]);
                temp = temp.next;
            }

            return head.next;
        }
    }

Find the Pivot Integer

Given a positive integer n, find the pivot integer x such that:

  • The sum of all elements between 1 and x inclusively equals the sum of all elements between x and n inclusively.

Return the pivot integer x. If no such integer exists, return -1. It is guaranteed that there will be at most one pivot index for the given input.

Example 1:

Input: n = 8
Output: 6
Explanation: 6 is the pivot integer since: 1 + 2 + 3 + 4 + 5 + 6 = 6 + 7 + 8 = 21.

Example 2:

Input: n = 1
Output: 1
Explanation: 1 is the pivot integer since: 1 = 1.

Example 3:

Input: n = 4
Output: -1
Explanation: It can be proved that no such integer exist.

Constraints:

  • 1 <= n <= 1000
public class Solution {
    public int PivotInteger(int n) {
        var arrLeftToRightSum = new int[1000];
        var arrRightToLeftSum = new int[1000];
        arrLeftToRightSum[0] = 1;
        arrRightToLeftSum[n - 1] = n;

        for(int i = 1; i < n; i++)
        {
            arrLeftToRightSum[i] = arrLeftToRightSum[i-1] + i + 1;
        }
        
        for(int i = n-2; i > 0; i--)
        {
            arrRightToLeftSum[i] = arrRightToLeftSum[i+1] + i + 1;
        }

        for(int i = 0; i < n; i ++)
        {
            if(arrLeftToRightSum[i] == arrRightToLeftSum[i])
            {
                return i+1;
            }
        }

        return -1;
    }
}

Custom Sort String

You are given two strings order and s. All the characters of order are unique and were sorted in some custom order previously.

Permute the characters of s so that they match the order that order was sorted. More specifically, if a character x occurs before a character y in order, then x should occur before y in the permuted string.

Return any permutation of s that satisfies this property.

Example 1:

Input: order = “cba”, s = “abcd”

Output: “cbad”

Explanation: "a", "b", "c" appear in order, so the order of "a", "b", "c" should be "c", "b", and "a".

Since "d" does not appear in order, it can be at any position in the returned string. "dcba", "cdba", "cbda" are also valid outputs.

Example 2:

Input: order = “bcafg”, s = “abcd”

Output: “bcad”

Explanation: The characters "b", "c", and "a" from order dictate the order for the characters in s. The character "d" in s does not appear in order, so its position is flexible.

Following the order of appearance in order, "b", "c", and "a" from s should be arranged as "b", "c", "a". "d" can be placed at any position since it’s not in order. The output "bcad" correctly follows this rule. Other arrangements like "bacd" or "bcda" would also be valid, as long as "b", "c", "a" maintain their order.

Constraints:

  • 1 <= order.length <= 26
  • 1 <= s.length <= 200
  • order and s consist of lowercase English letters.
  • All the characters of order are unique.
public class Solution {
    public string CustomSortString(string order, string s) {
        var dict = new Dictionary<char, int>();
        foreach(var ch in s)
        {
            if(dict.ContainsKey(ch))
            {
                dict[ch]++;
            }
            else
            {
                dict[ch] = 1;
            }
        }

        var resultArr = new char[s.Length];
        var index = 0;
        foreach(var ch in order)
        {
            if(dict.ContainsKey(ch))
            {
                for(int i = 0; i < dict[ch]; i++)
                {
                    resultArr[index++] = ch;
                }

                dict.Remove(ch);
            }
        }

        foreach(var item in dict)
        {
            for(int i = 0; i < item.Value; i++)
            {
                resultArr[index++] = item.Key;
            }
        }

        return new String(resultArr);
    }
}

Minimum Length of String After Deleting Similar Ends

Given a string s consisting only of characters 'a', 'b', and 'c'. You are asked to apply the following algorithm on the string any number of times:

  1. Pick a non-empty prefix from the string s where all the characters in the prefix are equal.
  2. Pick a non-empty suffix from the string s where all the characters in this suffix are equal.
  3. The prefix and the suffix should not intersect at any index.
  4. The characters from the prefix and suffix must be the same.
  5. Delete both the prefix and the suffix.

Return the minimum length of s after performing the above operation any number of times (possibly zero times).

Example 1:

Input: s = "ca"
Output: 2
Explanation: You can't remove any characters, so the string stays as is.

Example 2:

Input: s = "cabaabac"
Output: 0
Explanation: An optimal sequence of operations is:
- Take prefix = "c" and suffix = "c" and remove them, s = "abaaba".
- Take prefix = "a" and suffix = "a" and remove them, s = "baab".
- Take prefix = "b" and suffix = "b" and remove them, s = "aa".
- Take prefix = "a" and suffix = "a" and remove them, s = "".

Example 3:

Input: s = "aabccabba"
Output: 3
Explanation: An optimal sequence of operations is:
- Take prefix = "aa" and suffix = "a" and remove them, s = "bccabb".
- Take prefix = "b" and suffix = "bb" and remove them, s = "cca".

Constraints:

  • 1 <= s.length <= 105
  • s only consists of characters 'a', 'b', and 'c'.
public class Solution {
    public int MinimumLength(string s) {
        int start = 0, end = s.Length - 1;
        while(start < end)
        {
            if(s[start] != s[end])
            {
                break;
            }
            else
            {
                var ch = s[start];
                while(s[start] == ch && start < end)
                {
                    start++;
                }

                while(s[end] == ch && end >= start)
                {
                    end--;
                }
            }
        }
        
        return end - start + 1;
    }
}

Even Odd Tree

A binary tree is named Even-Odd if it meets the following conditions:

  • The root of the binary tree is at level index 0, its children are at level index 1, their children are at level index 2, etc.
  • For every even-indexed level, all nodes at the level have odd integer values in strictly increasing order (from left to right).
  • For every odd-indexed level, all nodes at the level have even integer values in strictly decreasing order (from left to right).

Given the root of a binary tree, return true if the binary tree is Even-Odd, otherwise return false.

Example 1:

Input: root = [1,10,4,3,null,7,9,12,8,6,null,null,2]
Output: true
Explanation: The node values on each level are:
Level 0: [1]
Level 1: [10,4]
Level 2: [3,7,9]
Level 3: [12,8,6,2]
Since levels 0 and 2 are all odd and increasing and levels 1 and 3 are all even and decreasing, the tree is Even-Odd.

Example 2:

Input: root = [5,4,2,3,3,7]
Output: false
Explanation: The node values on each level are:
Level 0: [5]
Level 1: [4,2]
Level 2: [3,3,7]
Node values in level 2 must be in strictly increasing order, so the tree is not Even-Odd.

Example 3:

Input: root = [5,9,1,3,5,7]
Output: false
Explanation: Node values in the level 1 should be even integers.

Constraints:

  • The number of nodes in the tree is in the range [1, 105].
  • 1 <= Node.val <= 106
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
public class Solution {
    public bool IsEvenOddTree(TreeNode root) {
        if(root.val % 2 == 0)
        {
            return false;
        }

        bool isOddLevel = true;
        var q = new Queue<TreeNode>();
        q.Enqueue(root);
        while(q.Count > 0)
        {
            var count = q.Count;
            var temp = 0;
            isOddLevel = !isOddLevel;
            for(var i = 0; i < count; i++)
            {
                var node = q.Dequeue();
                if(isOddLevel)
                {
                    if(node.val % 2 == 1)
                    {
                        return false;
                    }
                    else if(temp == 0)
                    {
                        temp = node.val;
                    }
                    else if(temp <= node.val)
                    {
                        return false;
                    }
                    else
                    {
                        temp = node.val;
                    }
                }
                else
                {
                    if(node.val % 2 == 0)
                    {
                        return false;
                    }
                    else if(temp == 0)
                    {
                        temp = node.val;
                    }
                    else if(temp >= node.val)
                    {
                        return false;
                    }
                    else
                    {
                        temp = node.val;
                    }
                }

                if(node.left != null)
                {
                    q.Enqueue(node.left);
                }

                if(node.right != null)
                {
                    q.Enqueue(node.right);
                }
            }
        }

        return true;
    }
}

Find Bottom Left Tree Value

Given the root of a binary tree, return the leftmost value in the last row of the tree.

Example 1:

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

Example 2:

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

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • -231 <= Node.val <= 231 - 1
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
public class Solution {
    public int FindBottomLeftValue(TreeNode root) {
        int result = root.val, count = 0;
        var q = new Queue<TreeNode>();
        q.Enqueue(root);
        while(q.Count > 0)
        {
            count = q.Count;
            for(int i = 0; i < count; i++)
            {
                var node = q.Dequeue();
                if(i == 0)
                {
                    result = node.val;
                }

                if(node.left != null)
                {
                    q.Enqueue(node.left);
                }

                if(node.right != null)
                {
                    q.Enqueue(node.right);
                }
            }
        }
        
        return result; 		
    }
}

Determine if Two Strings Are Close

Two strings are considered close if you can attain one from the other using the following operations:

  • Operation 1: Swap any two existing characters.
    • For example, abcde -> aecdb
  • Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character.
    • For example, aacabb -> bbcbaa (all a‘s turn into b‘s, and all b‘s turn into a‘s)

You can use the operations on either string as many times as necessary.

Given two strings, word1 and word2, return true if word1 and word2 are close, and false otherwise.

Example 1:

Input: word1 = "abc", word2 = "bca"
Output: true
Explanation: You can attain word2 from word1 in 2 operations.
Apply Operation 1: "abc" -> "acb"
Apply Operation 1: "acb" -> "bca"

Example 2:

Input: word1 = "a", word2 = "aa"
Output: false
Explanation: It is impossible to attain word2 from word1, or vice versa, in any number of operations.

Example 3:

Input: word1 = "cabbba", word2 = "abbccc"
Output: true
Explanation: You can attain word2 from word1 in 3 operations.
Apply Operation 1: "cabbba" -> "caabbb"
Apply Operation 2: "caabbb" -> "baaccc"
Apply Operation 2: "baaccc" -> "abbccc"

Constraints:

  • 1 <= word1.length, word2.length <= 105
  • word1 and word2 contain only lowercase English letters.
public class Solution {
    public bool CloseStrings(string word1, string word2) {
        if(word1.Length != word2.Length)
        {
            return false;
        }

        var arr1 = new int[26];
        var arr2 = new int[26];

        for(int i = 0; i < word1.Length; i++)
        {
            arr1[word1[i] - 'a']++;
            arr2[word2[i] - 'a']++;
        }

        for (int i = 0; i < 26; i++)
        {
            if (arr1[i] == 0 && arr2[i] != 0 || arr1[i] != 0 && arr2[i] == 0) 
            {
                return false;
            }
        }

        Array.Sort(arr1);
        Array.Sort(arr2);

        for(int i = 0; i < 26; i++)
        {
            if(arr1[i] != arr2[i])
            {
                return false;
            }
        }

        return true;
    }
}

Minimum Number of Steps to Make Two Strings Anagram

You are given two strings of the same length s and t. In one step you can choose any character of t and replace it with another character.

Return the minimum number of steps to make t an anagram of s.

An Anagram of a string is a string that contains the same characters with a different (or the same) ordering.

Example 1:

Input: s = "bab", t = "aba"
Output: 1
Explanation: Replace the first 'a' in t with b, t = "bba" which is anagram of s.

Example 2:

Input: s = "leetcode", t = "practice"
Output: 5
Explanation: Replace 'p', 'r', 'a', 'i' and 'c' from t with proper characters to make t anagram of s.

Example 3:

Input: s = "anagram", t = "mangaar"
Output: 0
Explanation: "anagram" and "mangaar" are anagrams.

Constraints:

  • 1 <= s.length <= 5 * 104
  • s.length == t.length
  • s and t consist of lowercase English letters only.
public class Solution {
    public int MinSteps(string s, string t) {
        var arr = new int[26];
        var result = 0;
        for(int i = 0; i < s.Length; i++)
        {
            arr[t[i] - 'a']++;
            arr[s[i] - 'a']--;
        }       

        foreach(var item in arr)
        {
            if(item > 0)
            {
                result+= item;
            }
        }

        return result;
    }
}