Posts

Showing posts from February, 2020

LeetCode: 169 Majority Element

LEETCODE : 169. Majority Element Link :  https://leetcode.com/problems/majority-element/ Problem Description :  Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. You may assume that the array is non-empty and the majority element always exist in the array. For example: Example 1: Input: [3,2,3] Output: 3   Example 2: Input: [2,2,1,1,1,2,2] Output: 2       ______________________________________________________________________________     Explaination :  There is pretty easy way to solve it by using count of every element and then returning the element which has count greater than n/2 . But this solution comes with a cost of O(n) time and O(n) space.  There is a better solution which can do the job in O(n) time and O(1) space. Atleast we are saving some of the space.  How does our space efficient algorithm works ? Basically, what we do is that we go

LEETCODE : 171. Excel Sheet Column Number

LEETCODE : 171. Excel Sheet Column Number Link : https://leetcode.com/problems/excel-sheet-column-number/ Problem Description :  Given a column title as appear in an Excel sheet, return its corresponding column number. For example: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ... Example 1: Input: "A" Output: 1     Example 2: Input: "AB" Output: 28 Example 3: Input: "ZY" Output: 701       ______________________________________________________________________________ Explaination :  Initially it looks like a hard problem but when we get to know the logic behind it then it seems to be a really easy problem. The observation needed here is that, the column title value represents a number of base 26. And all we need to do is to convert that base 26 number to base 10 number. To convert the base to base 10, we need to do what we usually do for binary or oc