Posts

Showing posts from September, 2021

Contains Duplicates

 Leetcode - 217/219/220 Contains Duplicate - I/II/III 1. Contains Duplicate - I https://leetcode.com/problems/contains-duplicate/ For example given an array [1,2,3,4,1] return true as 1 is repeated , return false all the elements in the array are unique.  Solution 1: Brute-Force method - O(n 2 ) time, O(1) space [TLE] While iterating the array check if the element  is repeated by comparing it with the rest of elements, if the values compared are equal return true. If the whole the array is traversed that means no element is repeated ,hence return false.                bool bruteForce(vector<int>& nums) {               for(int i = 0; i < nums.size(); ++i) {                   for(int j = i + 1; j < nums.size(); ++

Max Consecutive Ones

 Leetcode - 485/487/1004 Max Consecutive Ones - I/II/III 1. Max Consecutive Ones - I https://leetcode.com/problems/max-consecutive-ones/ Let us understand the problem with the following example. Say nums = [ 1, 1, 0, 1, 1, 1, 0, 1, 1 ]. Here the consecutive 1's lie in the following intervals - [0, 1], [3, 5] and [7, 8] each of length 2, 3 and 2 respectively. The expected result is max(2, 3, 2) = 3. Solution 1: Process one symbol at a time - O(n) time, O(1) space While iterating the array, if we hit a 0, that means the current streak of consecutive 1's is broken and the answer at that particular time is the max of the current streak and the previous maximum streak. Keeping this in mind, i terate the array and count the consecutive 1's and also the maximum number of consecutive 1's seen until that point and once we