Posts

Showing posts from July, 2021

Seats

 https://www.interviewbit.com/old/problems/seats/ int Solution::seats(string A) { for(int i=0;i<A.size();i++){ if(A[i]=='x') pos.push_back(i); } int n=pos.size(); long long int ans=0; int mid=n/2;int k=1; for(int i=mid-1;i>=0;i--){ ans=(ans+pos[mid]-k-pos[i])%10000003; k++; } k=1; for(int i=mid+1;i<n;i++){ ans=(ans+pos[i]-(pos[mid]+k))%10000003; k++; } return ans%10000003; } ...

Atoi

 https://www.interviewbit.com/old/problems/atoi/ while (str[i] == ' ' ) { i++; } if (str[i] == ' - ' || str[i] == ' + ' ) { sign = (str[i++] == ' - ' ) ? - 1 : 1 ; } while (str[i] >= ' 0 ' && str[i] <= ' 9 ' ) { if (base > INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - ' 0 ' > 7 )) { if (sign == 1 ) return INT_MAX; else return INT_MIN; } base = 10 * base + (str[i++] - ' 0 ' ); } return base * sign; int sign = 1 , base = 0 , i = 0 ; ...

Sort array with squares!

 https://www.interviewbit.com/old/problems/sort-array-with-squares/      vector<int> Solution::solve(vector<int> &arr) {         int mid=0;     for(int i=0;i<arr.size();i++)     {         if(arr[i]>=0)         {             mid=i;             break;         }     }     int i=mid-1,j=mid;     vector<int>res(arr.size());     int k=0;     while(i>=0 && j<arr.size())     {         if((arr[i]*arr[i])<(arr[j]*arr[j]))         {             res...

162. Find Peak Element

 https://leetcode.com/problems/find-peak-element/   class Solution { public:     int findPeakElement(vector<int>& nums) {         int l=0;         int r=nums.size()-1;         while(l<r)         {             int mid=(l+r)/2;                          if(nums[mid]>nums[mid+1])                 r=mid;             else                 l=mid+1;         }         return l;  ...

Perfect Peak of Array

  Given an integer array A of size N . You need to check that whether there exist a element which is strictly greater than all the elements on left of it and strictly smaller than all the elements on right of it. If it exists return 1 else return 0 .  https://www.interviewbit.com/old/problems/perfect-peak-of-array/ int Solution::perfectPeak(vector<int> &A) { int ans=-1; int l[A.size()]; int r[A.size()]; l[0]=A[0]; r[A.size()-1]=A[A.size()-1]; for(int i=1;i<A.size();i++){     l[i] = max(A[i],l[i-1]); } for(int i=A.size()-2;i>=0;i--){     r[i] = min(A[i],r[i+1]); } for(int i=1;i<A.size()-1;i++){     if(A[i]>l[i-1]&&A[i]<r[i+1]){         return 1;     } } if(ans==-1){     return 0; } }  

An Increment Problem

  Given a stream of numbers A . On arrival of each number, you need to increase its first occurence by 1 and include this in the stream. Return the final stream of numbers.  ip: A = [1, 1] op:  [2, 1]     vector<int> Solution::solve(vector<int> &a) {      unordered_map<int,int> m;     for(int i=0; i<a.size(); i++)     {         if(m.count(a[i]))         {             a[m[a[i]]]++;             m[a[i]+1] = m[a[i]];         }         m[a[i]] = i;     }     return a; }  

Rotate List

  ListNode* Solution::rotateRight(ListNode* A, int B) { ListNode* ptr = A; int len= 1 ; while (ptr-> next !=NULL){ ptr = ptr-> next ; len++; } B = B%len; if (B== 0 ) return A; ListNode* head, *temp, *start = A; int i= 1 ; ptr = A; while (i<len-B){ ptr = ptr-> next ; i++; } head = ptr-> next ; temp = head; while (temp-> next !=NULL) temp = temp-> next ; temp-> next = start; ptr-> next = NULL; return head; }

Merge Sorted Array

 class Solution { public:     void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {         int i = m-1, j = n-1, k = n+m-1;                  while(i>=0 && j>=0) {             if(nums1[i] >= nums2[j]) {                 nums1[k] = nums1[i];                 i--;             }             else {                 nums1[k] = nums2[j];                 j--;  ...

Integer To Roman

 string Solution::intToRoman(int A) {     int n[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};        string r[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};     auto i = 0;     string result = "";          while (A!=0)     {         while (A>=n[i])         {             result += r[i];             A -= n[i];         }         ++i;     }     return result; }

Vowel and Consonant Substrings!

  int Solution :: solve ( string A ) { long long v = 0 ; long long c = 0 ; long long ans = 0 ; long long mode = 1000000007 ; for ( int i = 0 ; i < A . size (); i ++ ) { if ( A [ i ] == 'a' || A [ i ] == 'e' || A [ i ] == 'i' || A [ i ] == 'o' || A [ i ] == 'u' ) { v ++ ; ans = ( ans + c ) % mode ; } else { c ++ ; ans = ( ans + v ) % mode ; } } return ( int ) ans ; }

Find First and Last Position of Element in Sorted Array

  Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. If target is not found in the array, return [-1, -1] .   Input: nums = [5,7,7,8,8,10], target = 8 Output: [3,4]  class Solution { public:     vector<int> searchRange(vector<int>& v, int b) {         int n=v.size();         int low=0;         int high=n-1;         int mid;         vector<int> ans(2);         ans[0]=-1;         ans[1]=-1;         while(low<=high)         {             mid=low+(high-low)/2;       ...

License Key Formatting

  You are given a license key represented as a string s that consists of only alphanumeric characters and dashes. The string is separated into n + 1 groups by n dashes. You are also given an integer k . We want to reformat the string s such that each group contains exactly k characters, except for the first group, which could be shorter than k but still must contain at least one character. Furthermore, there must be a dash inserted between two groups, and you should convert all lowercase letters to uppercase. Return the reformatted license key .   Input: s = "5F3Z-2e-9-w", k = 4 Output: "5F3Z-2E9W"   class Solution { public: string licenseKeyFormatting(string s, int k) { string ans; int n=k; for(int i=s.size()-1;i>=0;--i) { if(s[i] != '-') { if(n==0) { ans.push_back('-'); n=k; } ...

Remove Consecutive Characters

 Given a string A and integer B , remove all consecutive same characters that have length exactly B. A = "aabcd" B = 2 op: "bcd" string Solution::solve(string A, int B) { string ans=""; int i=0; int count=0; string t=""; for(i=0;i<A.length();i++){ t=t+A[i]; count++; if(A[i]!=A[i+1] ) { if(count!=B) ans=ans+t; t=""; count=0; } } return ans+t; }    

First Repeating element

 Given an integer array A of size N , find the first repeating element in it. We need to find the element that occurs more than once and whose index of first occurrence is smallest . If there is no repeating element, return -1.   int Solution::solve(vector<int> &A) {     int n=A.size();     unordered_map<int,int> m;     if(n==1) return -1;     for(int i=0;i<n;i++)     {         m[A[i]]++;     }     for(int i=0;i<n;i++)  if(m[A[i]]>1)return A[i];     return -1; } int Solution::solve(vector<int> &A) {     int n=A.size();     int min=-1;     unordered_map<int, int> b;     for(int i=n-1;i>=0;i--){         b[A[i]] +=1;        if(b[A[i]] > 1) min=A[i]; ...

Counting Valleys

 Given the sequence of up and down steps during a hike, find and print the number of valleys walked through.  ip: 8 UDDDUDUU op: 1   _/\ _ \ / \/\/     int   countingValleys ( int   n ,   string   s )   {    int   level = 0 ;    int   valley = 0 ;       for ( auto   c :   s )    {        if ( c == 'U' )        {            if ( level ==- 1 )            {                valley ++;            }            level ++;        }        else {      ...

Largest subarray with 0 sum

Given an array having both positive and negative integers. The task is to compute the length of the largest subarray with sum 0. Input: N = 8 A[] = {15,-2,2,-8,1,7,10,23} Output: 5 Explanation: The largest subarray with sum 0 will be -2 2 -8 1 7. int maxLen(int A[], int n) { int maxi=0; // store max length int sum=0; //stores the contiguous sum unordered_map<int,int>m; for(int i=0;i<n;i++) { sum+=A[i]; if(sum==0) // it is the largest sub array { maxi=i+1; } else{ if(m.find(sum)!=m.end()) //if we find the same sum that means it is a sub array with zero sum { maxi=max(maxi,i-m[sum]); } else{ m[sum]=i; //else update in hash map } } } return maxi; }      

Longest Consecutive Sequence

 Given an unsorted array of integers nums , return the length of the longest consecutive elements sequence.     int longestConsecutive(vector<int>& nums) {         set<int> hashSet;               //declared a set         for(int num: nums){             hashSet.insert(num);        //inserting all array element in the set         }         int  longestStreak=0;         for(int num: nums){             if(!hashSet.count(num-1)){           //if the number does not has the previous number the update    ...

Pascal's Triangle II

 Given an integer rowIndex , return the rowIndex th ( 0-indexed ) row of the Pascal's triangle .       vector<int> getRow(int rowIndex) {         vector<int> v(rowIndex+1,1);                for(int i=1;i<rowIndex;++i)         {             for(int j=i;j>0;--j)             {                 v[j]=v[j]+v[j-1];             }         }                  return v;     }

Colorful Number

  Check if the product of every contiguous subsequence is different or not in a number N = 23 2 3 23 2 -> 2 3 -> 3 23 -> 6 this number is a COLORFUL number since product of every digit of a sub-sequence are different. Output : 1    int Solution::colorful(int A) {    string s= to_string(A); //convert the number to string    int n=s.size(); //size of the string    map<long long,bool> m; //map initialize    for(auto i=0;i<n;i++)  //iteration to find mul of all subsequence    {        long long int mul=1;        for(auto j=i;j<n;j++)        {            mul*=(long long int)(s[j]-'0'); //subtracted by '0' because its a string by subtracting with string it  //will be integer            if(m.find(mul)!=m.end())...

Pascal's Triangle

Input: numRows = 5 Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]  //each  nth row has n numbers // first and last no is always 1                          1                     1          1               1           2           1          1         3          3            1  vector<vector<int>> generate(int numRows) {         vector<vector<int>> r(numRows);           ...

Sorted Insert Position

  Given a sorted array A and a target value B , return the index if the target is found. If not, return the index where it would be if it were inserted in order. You may assume no duplicates in the array.   int searchInsert ( vector < int > & A , int target ) { int n = A . size (); int start = 0 , end = n - 1 ; int mid ; while ( start <= end ){ mid = ( start + end ) / 2 ; if ( target == A [ mid ]){ return mid ; } else if ( target < A [ mid ]){ end = mid - 1 ; } else { start = mid + 1 ; } } return start ; }  

Smaller or equal elements

Given an sorted array A of size N . Find number of elements which are less than or equal to B .   int Solution::solve(vector<int> &A, int B) {     int start=0;     int ans=0;     int end=A.size()-1;          while(start<=end)     {         int mid=(end+start)/2;                 if(A[mid]<=B)        {            ans=mid+1;            start=mid+1;        }        else{            end=mid-1;        }     }     return ans; }

Day of the Programmer (HackerRank)

  string dayOfProgrammer( int  year) {     string res="";           if (year==1918)          {              res=  "26.09.1918\n";          }           else {               if ((year < 1918 && year%4==0)||(year%400==0) || (year%4==0&&year%100!=0))              {                  res= "12.09."+to_string(year);              }        ...

Excel Sheet Column Title

   Given an integer columnNumber , return its corresponding column title as it appears in an Excel sheet . A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ...     string convertToTitle(int columnNumber ) {         string res="";         while(n--)         {             res+='A'+ (char)(n%26);             n=n/26;         }         reverse(res.begin(),res.end());         return res;     }

Distribute Candies to People

     vector<int> distributeCandies(int candies, int n) {         vector<int> res(n);         for (int i = 0; candies > 0; ++i) {             res[i % n] += min(candies, i + 1);             candies -= i + 1;         }         return res;     }   vector < int > distributeCandies ( int candies, int num_people) { int c = 1 , i = 0 ; vector < int > result (num_people, 0 ) ; while (candies) { int give = min(c, candies); result[i] += give; candies -= give; c++; i = (i+ 1 ) % num_people; } return result; }  

Subarrays with distinct integers!

  Given an array A of positive integers,call a (contiguous,not necessarily distinct) subarray of A good if the number of different integers in that subarray is exactly B . (For example: [1, 2, 3, 1, 2] has 3 different integers 1, 2 and 3) Return the number of good subarrays of A .  input A = [1, 2, 1, 3, 4] B = 3  output 7    Subarrays formed with exactly 3 different integers: [1, 2, 1, 3], [2, 1, 3], [1, 3, 4].   int Solution::solve(vector<int> &A, int B) { unordered_map<int, int> m; int res = 0, j=0, prefix = 0, cnt=0; for(auto i = 0; i < A.size(); ++i) {     if (m[A[i]]++ == 0)         ++cnt;     if (cnt > B){         --m[A[j++]];         --cnt;         prefix = 0;     }     while (m[A[j]] > 1){     ...

Add Binary

 Given two binary strings a and b , return their sum as a binary string .           int i = a.size() - 1;         int j = b.size() - 1;         int carry=0;         string result = "";         while (i >= 0 || j >= 0 ) {             int sum=carry;             if (i >= 0 ) sum+=a[i--]-'0'; // its given in string to convert in integer we subtract it with '0'             if (j >= 0 ) sum+=b[j--]-'0';             carry=sum>1?1:0;             result+=to_string(sum%2);         }   ...

Best Time to Buy and Sell Stocks I

 Say you have an array, A , for which the i th element is the price of a given stock on day i . If you were only permitted to complete at most one transaction (i.e, buy one and sell one share of the stock), design an algorithm to find the maximum profit. Return the maximum possible profit. Input 1: A = [1, 2] Output 1: 1     int  Solution::maxProfit( const  vector< int > &arr) {      int  maxprof= 0 ;      int  minimum=INT_MAX;      for ( int  i= 0 ;i<arr.size();i++)     {         minimum=min(minimum,arr[i]);         maxprof=max(maxprof,arr[i]-minimum);              }           return  maxprof; }

Length of Last Word

Given a string s consists of some words separated by spaces, return the length of the last word in the string. If the last word does not exist, return 0 .     int lengthOfLastWord(string s) {        int ans=0;         for(int i=s.length()-1;i>=0;i--)         {             if(s[i]==' ' && ans>0) return ans;             if(s[i]!=' ' )ans++;         }         return ans;              }   int lengthOfLastWord(string s) {        int len = 0, tail = s.length() - 1;         while (tail >= 0 && s[tail] == ' ') tail--;       ...

Stair Case Problem (DP)

  You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Example : Input : 3 Return : 3 Steps : [1 1 1], [1 2], [2 1] int Solution::climbStairs(int n) { int dp[n]; if(n==0) return 1; dp[0]=1; dp[1]=2; for(int i=2;i<n;i++){ dp[i]=dp[i-1]+dp[i-2]; } return dp[n-1]; ...

Maximum Subarray

 Kadane's Algorithm  int maxSubArray(vector<int>& a) {         int max_so_far = INT_MIN, max_ending_here = 0;           for (int i = 0; i < a.size(); i++)        {         max_ending_here = max_ending_here + a[i];         if (max_so_far < max_ending_here)             max_so_far = max_ending_here;           if (max_ending_here < 0)             max_ending_here = 0;        }            return max_so_far;     }