Monday, March 1, 2021

Leetcode Everyday: 832. Flipping an Image. Easy

public class Solution {
    public int[][] FlipAndInvertImage(int[][] image) {
        foreach (var row in image) {
            for (var col = 0; col < row.Length / 2; ++col) {                
                // shorthand:
                (row[col], row[^(col+1)]) = (row[^(col+1)], row[col]);
                
                // longhand:
                // (row[col], row[row.Length - (col+1)]) = (row[row.Length - (col+1)], row[col]);
            }            
            
            for (var col = 0; col < row.Length; ++col) {
                row[col] ^= 1;
            }
        }
        
        return image;
    }
}
Optimized:
public class Solution {
    public int[][] FlipAndInvertImage(int[][] image) {
        foreach (var row in image) {
            var half = row.Length / 2;
            for (var col = 0; col < half; ++col) {                
                // shorthand:
                (row[col], row[^(col+1)]) = (row[^(col+1)] ^ 1, row[col] ^ 1);
                
                // longhand:
                // (row[col], row[row.Length - (col+1)]) = (row[row.Length - (col+1)], row[col]);
            }                        
        }
        
        if (image.Length > 0 && image[0].Length % 2 == 1) {
            var middle = image[0].Length / 2;
            foreach (var row in image) {
                row[middle] ^= 1;
            }
        }
        
        return image;
    }
}
Source: https://leetcode.com/problems/flipping-an-image/

Friday, February 26, 2021

Leetcode Everyday: 1252. Cells with Odd Values in a Matrix

public class Solution {
    public int OddCells(int n, int m, int[][] indices) {
        var mat = new int[n, m];
        
        foreach (var index in indices) {
            var ri = index[0];                
            for (var col = 0; col < m; ++col) {
                ++mat[ri, col];
            }
            
            var ci = index[1];
            for (var row = 0; row < n; ++row) {
                ++mat[row, ci];
            }
        }
        
        // this would work:
        // var oddCount = 0;
        // for (var ni = 0; ni < n; ++ni) {
        //     for (var mi = 0; mi < m; ++mi) {
        //         oddCount += mat[ni, mi] % 2;
        //     }
        // }
        
        // functional programming:
        // return mat.Cast<int>().Count(number => number % 2 == 1);
        
        // this is better and faster. C# can look at array as if it is one-dimensional
        var oddCount = 0;
        foreach (var number in mat) {
            oddCount += number % 2;
        }        
        return oddCount;
    }
}
Source: https://leetcode.com/problems/cells-with-odd-values-in-a-matrix/

Wednesday, February 24, 2021

Leetcode Everyday: 804. Unique Morse Code Words. Easy

Functional programming:
public class Solution {
    readonly string[] morseCodes = new[] {
        ".-","-...","-.-.","-..",".",
        "..-.","--.","....","..",".---",
        "-.-",".-..","--","-.","---",
        ".--.","--.-",".-.","...","-",
        "..-","...-",".--","-..-","-.--","--.."
    };
    
    public int UniqueMorseRepresentations(string[] words) =>
        words.Select(word =>
            word.Skip(1).Aggregate(
                morseCodes[word[0] - 'a'].ToString(),
                (txMorse, current) => txMorse + morseCodes[current - 'a']
            )
        ).Distinct().Count();    
}
Imperative programming:
public class Solution {

    public int UniqueMorseRepresentations(string[] words) {        
        var morseCodes = new[] {
            ".-","-...","-.-.","-..",".",
            "..-.","--.","....","..",".---",
            "-.-",".-..","--","-.","---",
            ".--.","--.-",".-.","...","-",
            "..-","...-",".--","-..-","-.--","--.."
        };
        
		var distinctMorses = new HashSet();
        var buildMorse = new StringBuilder();
        foreach (var word in words) {
        
            foreach (var c in word) {
                buildMorse.Append(morseCodes[c - 'a']);
            }
            
            var txMorse = buildMorse.ToString();
            buildMorse.Clear();
            
            if (!distinctMorses.Contains(txMorse)) {
                distinctMorses.Add(txMorse);
            }
        }        
        return distinctMorses.Count;
    }      
          
}
Source: https://leetcode.com/problems/unique-morse-code-words/

Tuesday, February 23, 2021

Leetcode Everyday: 1021. Remove Outermost Parentheses. Easy

public class Solution {
    public string RemoveOuterParentheses(string s) {
        var sb = new StringBuilder();        
    
        var opList = new Dictionary<char, int> {
            ['('] = 1,
            [')'] = -1
        };
        
        int depth = 0;
        foreach (var c in s) {
            var op = opList[c];
            depth += op;
            if (op == 1 && depth > 1 || op == -1 && depth > 0) {
                sb.Append(c);
            }
        }
        
        return sb.ToString();
    }
}
Compact condition:
public class Solution {
    public string RemoveOuterParentheses(string s) {
        var sb = new StringBuilder();
         
     
        // KeyValue<op, depth>
        // op = 1 = increment
        // op = -1 = decrement
        var opList = new Dictionary<char, KeyValuePair<int, int>> {
            ['('] = new KeyValuePair<int, int>(1, 1),
            [')'] = new KeyValuePair<int, int>(-1, 0)
        };
         
         
        int depth = 0;
        foreach (var c in s) {
            var (op, opDepth) = opList[c];
            depth += op;
                  
            if (depth > opDepth) {
                sb.Append(c);
            }
        }
         
        return sb.ToString();
    }
}
Source: https://leetcode.com/problems/remove-outermost-parentheses/

Monday, February 22, 2021

Leetcode Everyday: 1295. Find Numbers with Even Number of Digits. Easy

Functional programming:
using static System.Math;

public class Solution {
    public int FindNumbers(int[] nums) =>
        nums.Count(num => CountDigit(num) % 2 == 0);
    
    public int CountDigit(int n) => (int)Max(Log10(n), 0) + 1;
}
Imperative programming:
using static System.Math;

public class Solution {
    public int FindNumbers(int[] nums) {
        int evenCount = 0;
        foreach (var num in nums) {
            if (CountDigit(num) % 2 == 0) {
                ++evenCount;
            }  
        }
        return evenCount;
        
        int CountDigit(int num) {            
            int digit = 0;
            for (; num != 0; num /= 10) {
                ++digit;
            }
            return Max(digit, 1);
        }
    }
}
Source: https://leetcode.com/problems/find-numbers-with-even-number-of-digits/submissions/