Profile picture
Long Pham
November 23, 2024

LeetCode Solutions

796. Rotate String


Honestly, I only took this because it was a daily question. Didn't see another approach so I went with brute-forcing. It does surprise me that the runtime was 0ms, but consider the input strings are 100 characters at max, I think it's reasonable. Anyways, here's the solution:
c#
public class Solution {
    public bool RotateString(string s, string goal) {
        if(s.Length != goal.Length) return false;
        if(s == goal) return true;
        // temporary copy of the original string content
        var iter = s;

        while(true) {
            iter = iter.Substring(1, iter.Length - 1) + iter[0];
            if(iter == goal) return true;
            if(iter == s) return false;
        }
        
        return false;
    }
}
You probably can figure this out on your own quite easily.

1523. Count Odd Numbers in an Interval Range


Another range problem. My approach to this is to push low to the same ending digit as high and count the number of odds in the process. For example, let's say if low is 3 and high is 27, we push 3 to 7 and count (3, 5, 7) in the process. This is to ensure that the difference is now divisible by 10. Afterwards, just divide the diff by 2.
c#
public class Solution {
    public int CountOdds(int low, int high) {
        int diff = high - low;
        int count = 0;

        // push low to the same last digit as high
        // so that the diff is divisible by 10
        for(int i = low; i <= low + (diff % 10); ++i) {
            if(i % 2 == 1 ) {
                count++;
            }
        }

        // subtract the accounted part above
        diff -= (diff % 10);

        // 5 odd numbers in every 10 numbers
        count += (diff / 2);

        return count;       
    }
}
The code performed quite well, dropping in at about 80% percentile (unsure how credible is LeetCode's evaluation system though).

1837. Sum of Digits in Base K


The description was clear and concise. Convert the number n to base k and calculate the sum of all the digits in the converted number representation.
c#
public class Solution {
    public int SumBase(int n, int k) {
        var converted = String.Empty;
        int ans = 0;

        // Convert to base k
        while(n / k != 0) {      
            converted = converted + (n % k).ToString();   
            n /= k;
        }
        converted += (n % k).ToString();

        // calculate sum of digits
        foreach(char ch in converted) {
            ans += Int32.Parse(ch.ToString());
        }

        return ans;
        
    }
}
Ngl, I had to look up how to convert decimals to an arbitrary base representation to do this question. I found this article quite helpful but I'm sure you can understand the mechanism after 5 minutes of reading. Solution was clean and fast, but not that it's super difficult for anyone.

2099. Find Subsequence of Length K With the Largest Sum


An interesting question, to say the least. I thought about retrieving the top k values from the array and call it a day, but order matters in this one. This is my working solution:
c#
public class Solution {
    public int[] MaxSubsequence(int[] nums, int k) {
        var ans = new SortedDictionary<int, int>();
        while(ans.Count < k) {
            var max = nums.Max();
            var idx = Array.IndexOf(nums, max);
            ans.Add(idx, max);
            nums[idx] = Int32.MinValue;
        }
        return ans.Values.ToArray();
    }
}
Probably not the cleanest, but it works just fine. Here, through each iteration, we retrieve the max value of the list, add it to the sorted dictionary and just set the max value to Int32.MinValue. I used the SortedDictionary with array indices as keys in order to keep the order in check, ensuring that the result array is a valid subsequence of the original one. Afterwards, we should have a list with preserved order and we just need to return the dictionary values (and, convert it to an array). Not super performant, but it did the job. A priority queue will probably work better here.

2119. A Number After a Double Reversal


One of those problems that made me question if I missed some edge cases because it can't be this easy. Well, it is. My first thought was just checking if the number was divisible by 10 (i.e the number ends with one or more 0s). 0 was an edge case so it was handled with a simple if check.
typescript
function isSameAfterReversals(num: number): boolean {
    return num === 0 ? true : num % 10 !== 0;
};

2154. Keep Multiplying Found Values by Two

c#
public class Solution {
    public int FindFinalValue(int[] nums, int original) {
        while(Array.IndexOf(nums, original) != -1) {
            original *= 2;
        }
        return original; 
    }
}

2180. Count Integers With Even Digit Sum


The key to solving this one is knowing that every ten numbers, there are 5 of them whose digits add up to an even number. This helps majorly as I divided the number by 10, multiple by 5 and I already have the count of all numbers before the ending tenth. To put it simple, if num was 413 then the division already gave me the count of numbers satisfying the condition in range [0:409]. This left me with [410:413] to handle.
c#
public class Solution {
    public int CountEven(int num) {
        int count = 0;

        int lastDigit = num % 10;
        int countOfTens = num / 10;
        int allDigitsSum = 0;
        
        // every ten numbers, there are 5 whose digits sum will be even. 
        // -1 for the first of the ending tenth 
        count += countOfTens * 5 - 1;

        foreach(char digit in num.ToString()) {
            allDigitsSum += digit;
        }

        // the ending tenth
        for(int i = 0; i <= lastDigit; ++i) {
            if(allDigitsSum % 2 == 0 && i %2 == 0) count++;
            else if(allDigitsSum % 2 != 0 && i % 2 != 0) count++; 
        }
        
        return count;
    }
}
Handling the ending tenth is just the matter of determining the sum of all digits. If the sum of all digits was even, we traverse from 0 to the last digit and count all even numbers (0, 2, 4, 6, 8). Vice versa, we count the odd ones (1, 3, 5, 7, 9). Problem solved! I do think this is quite optimal as a solution for this specific problems. Some twitch here and there is possible but probably not gonna make it noticeably faster.

2325. Decode the Message


A perfect use case for Dictionary, I'd say (some call it a Map).
c#
public class Solution {
    public string DecodeMessage(string key, string message) {
        var retVal = String.Empty;
        var dict = new Dictionary<char, char>();

        // populates the dictionary
        foreach(var ch in key) {
            if(ch != ' ' && !dict.ContainsKey(ch)) {
                // 'a' starts at 97 in the ascii table so we add it up and then convert it back to char type
                dict.Add(ch, Convert.ToChar(dict.Count + 97));
            }
        }

        // constructing a new string by substituting
        foreach(var ch in message) {
            if(dict.ContainsKey(ch)) {
                retVal += dict[ch];
            } else {
                retVal += ch;
            }
        }

        return retVal;
    }
}
We traverse through the key string, map it out in the dictionary. After that is done, we go through the message and decode it. If the character is in the dictionary, we append the decoded character. Else we just add the raw character to the string. Simple and easy enough to understand.

2351. First Letter to Appear Twice


I went with the most simple approach: have a vector of letters that appeared in the string, check if the character was in the vector and return it. No crazy sciences.
c#
class Solution {
public:
    char repeatedCharacter(string s) {
        vector<char> encounteredChars = {};
        for(int i = 0; i < s.size(); ++i) {
            if(find(encounteredChars.begin(), encounteredChars.end(), s[i]) != encounteredChars.end()) return s[i];
            encounteredChars.push_back(s[i]); 
        }
        return s[0];
    }
};

2437. Number of Valid Clock Times


Not much DS knowledge or anything necessary here, just basic logic for this question. Here's what I had:
c#
public class Solution {
    public int CountTime(string time) {
        var timeParts = time.Split(':');
        var h1 = timeParts[0][0];
        var h2 = timeParts[0][1];
        var m1 = timeParts[1][0];
        var m2 = timeParts[1][1];

        return CountHours(h1, h2) * CountMinutes(m1, m2);
    }

    private int CountHours(char h1, char h2) {
        if (h1 == '?' && h2 == '?') {
            return 24;
        }
        if (h1 == '?') {
            if(h2 <= '3') {
                return 3;
            } else {
                return 2;
            }
        }
        if (h2 == '?') {
            if(h1 == '2') return 4;
            else return 10; 
        }

        return 1;
    }

    private int CountMinutes(char m1, char m2) {
        if(m1 == '?' && m2 == '?') {
            return 60;
        }
        if (m1 == '?') {
            return 6;
        }
        if (m2 == '?') {
            return 10;
        }

        return 1;
    }
}

2486. Append Characters to String to Make Subsequence


One of the more affordable normal difficulty questions for me. The hint gave great direction to solving this. Double pointers to traverse through both strings and count how many characters of t appeared in s and return the length of the characters that were not found.
c#
public class Solution {
    public double MinimumAverage(int[] nums) {
        double minAvg = double.MaxValue;
        Array.Sort(nums);
        for(int i = 0; i < nums.Length / 2; ++i) {
            var min = nums[i];
            var max = nums[nums.Length - i - 1];
            var tmp = (min + max) * 1.0 / 2;
            if(minAvg > tmp) minAvg = tmp;
        }
        return minAvg;
    }
}

3194. Minimum Average of Smallest and Largest Elements


The constraint is important in how we should approach this problem. The nums array is limited to 50 members at max. This ensures sorting is not super bad for performance, and the gain from sorting the array helps solving the problem easily so I proceeded to do that. The solution is as follow:
c#
public class Solution {
    public double MinimumAverage(int[] nums) {
        double minAvg = double.MaxValue;
        Array.Sort(nums);
        for(int i = 0; i < nums.Length / 2; ++i) {
            var min = nums[i];
            var max = nums[nums.Length - i - 1];
            var tmp = (min + max) * 1.0 / 2;
            if(minAvg > tmp) minAvg = tmp;
        }
        return minAvg;
    }
}
The description misled me into having an array of averages, but that's not the optimal solution. Instead having a min variable was sufficient. This came in at 0ms, I think it can hardly be more optimized.

3270. Find the Key of the Numbers


I went with this most intuitive solution for this problem (or at least the most intuitive to me): pad the number, loop through and construct the result string before parsing it back to int. Works well enough for me.
c#
public class Solution {
    public int GenerateKey(int num1, int num2, int num3) {
        const int LENGTH = 4;
        var res = String.Empty;

        var n1Digits = num1.ToString().PadLeft(LENGTH, '0').ToCharArray();
        var n2Digits = num2.ToString().PadLeft(LENGTH, '0').ToCharArray();
        var n3Digits = num3.ToString().PadLeft(LENGTH, '0').ToCharArray();

        for(int i = 0; i < LENGTH; ++i) {
            // Subtract 48 to convert char to int. Unethical but it works and it's fast.
            res += Math.Min(Math.Min(n1Digits[i], n2Digits[i]), n3Digits[i]) - 48;
        }

        return Int32.Parse(res);
    }
}
Comes in at about 47% percentile, but it was at 1ms vs 0ms.

© 2025 Long Pham. All Rights Reserved.