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:
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;
}
}
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.
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;
}
}
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.
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;
}
}
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:
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();
}
}
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.
function isSameAfterReversals(num: number): boolean {
return num === 0 ? true : num % 10 !== 0;
};
2154. Keep Multiplying Found Values by Two
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.
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;
}
}
2325. Decode the Message
A perfect use case for Dictionary, I'd say (some call it a Map).
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;
}
}
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.
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:
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.
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:
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;
}
}
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.
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);
}
}