Monday, March 21, 2022

Integer to Roman Leetcode Solution

 12. Integer to Roman Leetcode Solution

Medium

Roman numerals are represented by seven different symbols: IVXLCD and M.

Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

  • I can be placed before V (5) and X (10) to make 4 and 9. 
  • X can be placed before L (50) and C (100) to make 40 and 90. 
  • C can be placed before D (500) and M (1000) to make 400 and 900.

Given an integer, convert it to a roman numeral.

 

Example 1:

Input: num = 3
Output: "III"
Explanation: 3 is represented as 3 ones.

Example 2:

Input: num = 58
Output: "LVIII"
Explanation: L = 50, V = 5, III = 3.

Example 3:

Input: num = 1994
Output: "MCMXCIV"
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

 

Constraints:

  • 1 <= num <= 3999
Practice here :

Solution:

class Solution {
public:
    string intToRoman(int num) {
        string ans ="";
        
        while(num>0)
        {
            
        if(num>=1000)
        {
            ans+='M';
            num-=1000;
        }else if(num>=900)
        {
            ans+="CM";
            num-=900;
        }else if(num>=500)
        {
            ans+='D';
            num-=500;
        }else if(num>=400)
        {
            ans+="CD";
            num-=400;
        }else if(num>=100)
        {
            ans+='C';
            num-=100;
        }
            else if(num>=90)
        {
            ans+="XC";
            num-=90;
        }
            else if(num>=50)
        {
            ans+='L';
            num-=50;
        }
            else if(num>=40)
        {
            ans+="XL";
            num-=40;
        }
            else if(num>=10)
        {
            ans+='X';
            num-=10;
        }else if(num>=9)
        {
            ans+="IX";
            num-=9;
        }
             else if(num>=5)
        {
            ans+='V';
            num-=5;
        }else if(num>=4)
        {
            ans+="IV";
            num-=4;
        }
            else if(num>=1)
        {
            ans+='I';
            num-=1;
        }
            
        }
        return ans;
    }
};

Leetcode 38 Count and say solution

38. Count and Say

Medium

The count-and-say sequence is a sequence of digit strings defined by the recursive formula:

  • countAndSay(1) = "1"
  • countAndSay(n) is the way you would "say" the digit string from countAndSay(n-1), which is then converted into a different digit string.

To determine how you "say" a digit string, split it into the minimal number of groups so that each group is a contiguous section all of the same character. Then for each group, say the number of characters, then say the character. To convert the saying into a digit string, replace the counts with a number and concatenate every saying.

For example, the saying and conversion for digit string "3322251":

Given a positive integer n, return the nth term of the count-and-say sequence.

 

Example 1:

Input: n = 1
Output: "1"
Explanation: This is the base case.

Example 2:

Input: n = 4
Output: "1211"
Explanation:
countAndSay(1) = "1"
countAndSay(2) = say "1" = one 1 = "11"
countAndSay(3) = say "11" = two 1's = "21"
countAndSay(4) = say "21" = one 2 + one 1 = "12" + "11" = "1211"

 

Constraints:

  • 1 <= n <= 30

Practice Here :

(9) Count and Say - LeetCode

Solution :

#include <bits/stdc++.h>

class Solution {

public:

    string say(string n)

    {   string ans="";

        int ct =1;

        char c = n[0];

        for(int i=1;i<n.length();i++)

        {

            if(n[i]!=c)

            {

               ans+=(ct+'0');

                ans+=(c);

                ct =1;

                c = n[i];

            }else {

                ct++;

            }

        }

     ans+=(ct+'0');

        ans+=(c);

     return ans;

    }

    string countAndSay(int n) {

       vector<string> v;

        v.push_back("0");

        v.push_back("1");

        for(int i=2;i<=n;i++)

        {  

            v.push_back(say(v[i-1]));

        }

        return v[n];

    }

};

    Leetcode pow(x,n) solution

     50. Pow(x, n)

    Medium

    Implement pow(x, n), which calculates x raised to the power n (i.e., xn).

     

    Example 1:

    Input: x = 2.00000, n = 10
    Output: 1024.00000
    

    Example 2:

    Input: x = 2.10000, n = 3
    Output: 9.26100
    

    Example 3:

    Input: x = 2.00000, n = -2
    Output: 0.25000
    Explanation: 2-2 = 1/22 = 1/4 = 0.25
    

     

    Constraints:

    • -100.0 < x < 100.0
    • -231 <= n <= 231-1
    • -104 <= xn <= 104
    Practice Here :

    Solution :

    class Solution {
    public:
        double myPow2(double x,long long int n) {
            if(n==0||x==1)
                return 1;
            else if(n==1)
                return x;
            else if(n<0)
            {
                return 1/myPow2(x,n/-1);
            }
            else if(n%2==0)
                return myPow2(x*x,n/2);
            else return myPow2(x*x,n/2)*x;
        }
        double myPow(double x, int n) {
            return myPow2(x,n);
        }
    };

    Saturday, March 19, 2022

    Find majority element - GFG practice solution

    Given an array A of N elements. Find the majority element in the array. A majority element in an array A of size N is an element that appears more than N/2 times in the array.

     

    Example 1:

    Input:
    N = 3 
    A[] = {1,2,3} 
    Output:
    -1
    Explanation:
    Since, each element in 
    {1,2,3} appears only once so there 
    is no majority element.
    

    Example 2:

    Input:
    N = 5 
    A[] = {3,1,3,3,2} 
    Output:
    3
    Explanation:
    Since, 3 is present more
    than N/2 times, so it is 
    the majority element.
    


    Your Task:
    The task is to complete the function majorityElement() which returns the majority element in the array. If no majority exists, return -1.

     

    Expected Time Complexity: O(N).
    Expected Auxiliary Space: O(1).

     

    Constraints:
    1 ≤ N ≤ 107

    0 ≤ Ai ≤ 106



    Practice Here :


    Majority Element | Practice | GeeksforGeeks


    Solution:


    class Solution{

      public:

         // Function to find majority element in the array

        // a: input array

        // size: size of input array

        int majorityElement(int a[], int size)

        {

            

            // your code here

            int k =size/2;

            unordered_map<int,int> mp;

            for(int i=0;i<size;i++)

            {

                mp[a[i]]++; //store the count of all elements here in the map

            }

            

            for(auto it : mp)

            {

                if(it.second>k) //check whose count is greater than n/2

                return it.first;

            }

            return -1;

        }

    };

    Thursday, March 17, 2022

    Spirally traversing a matrix GFG Solution

    Spirally traversing a matrix 
    Medium 

    Given a matrix of size r*c. Traverse the matrix in spiral form.

    Example 1:

    Input:
    r = 4, c = 4
    matrix[][] = {{1, 2, 3, 4},
               {5, 6, 7, 8},
               {9, 10, 11, 12},
               {13, 14, 15,16}}
    Output: 
    1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
    Explanation:
    

    Example 2:

    Input:
    r = 3, c = 4  
    matrix[][] = {{1, 2, 3, 4},
               {5, 6, 7, 8},
               {9, 10, 11, 12}}
    Output: 
    1 2 3 4 8 12 11 10 9 5 6 7
    Explanation:
    Applying same technique as shown above, 
    output for the 2nd testcase will be 
    1 2 3 4 8 12 11 10 9 5 6 7.
    


    Your Task:
    You dont need to read input or print anything. Complete the function spirallyTraverse() that takes matrix, r and c as input parameters and returns a list of integers denoting the spiral traversal of matrix. 

    Expected Time Complexity: O(r*c)
    Expected Auxiliary Space: O(r*c), for returning the answer only.

    Constraints:
    1 <= r, c <= 100
    0 <= matrixi <= 100


    Practice Here:

    Spirally traversing a matrix | Practice | GeeksforGeeks

    Solution :

    class Solution

    {   

        public: 

        //Function to return a list of integers denoting spiral traversal of matrix.

        vector<int> spirallyTraverse(vector<vector<int> > matrix, int r, int c) 

        {

            vector<int> v;

            int minRow =0;

            int maxRow = r-1;

            int maxCol = c-1;

            int minCol = 0;

            int i = minRow;

            int j = minCol;

            while(minRow<=maxRow||minCol<=maxCol){

                //cout<<i<<" j:"<<j<<endl;

                while((j<=maxCol&&j>=minCol)&&(i<=maxRow&&i>=minRow))

                v.push_back(matrix[i][j++]);

                minRow++;

                j--;

                i++;

             //cout<<i<<" j:"<<j<<endl;

                while((j<=maxCol&&j>=minCol)&&(i<=maxRow&&i>=minRow))

                v.push_back(matrix[i++][j]);

                maxCol--;

                j--;

                i--;

            //cout<<i<<" j:"<<j<<endl;

                while((j<=maxCol&&j>=minCol)&&(i<=maxRow&&i>=minRow))

                    v.push_back(matrix[i][j--]);

                    maxRow--;

                i--; 

                j++;

             //cout<<i<<" j:"<<j<<endl;

                while((j<=maxCol&&j>=minCol)&&(i<=maxRow&&i>=minRow))

                  v.push_back(matrix[i--][j]);

                  minCol++;

              j++;

              i++;

              

            }

            return v;

        }

    };


    Reverse a string using Stack GFG Solution

     Reverse a string using Stack 

    Easy 

    You are given a string S, the task is to reverse the string using stack.

     

    Example 1:

    Input: S="GeeksforGeeks"
    Output: skeeGrofskeeG

     

    Your Task:
    You don't need to read input or print anything. Your task is to complete the function reverse() which takes the string as an input parameter and returns the reversed string.

     

    Expected Time Complexity: O(N)
    Expected Auxiliary Space: O(N)

     

    Constraints:
    1 ≤ length of the string ≤ 100

    Practice Here:

    Parenthesis Checker | Practice | GeeksforGeeks


    Solution:


    class Solution

    {

        public:

        //Function to check if brackets are balanced or not.

        bool ispar(string x)

        {

            // Your code here

            stack<char> st;

            for(char c: x)

            {

                if(c=='('||c=='{'||c=='[')

                st.push(c);

                else {

                    if(st.empty())

                    return false;

                    if((c==')'&&st.top()=='(')||(c=='}'&&st.top()=='{')||(c==']'&&st.top()=='['))

                    st.pop();

                    else return false;

                }

            }

            

           return st.empty();

        }


    };

    Implement stsStr Leetcode solution

      28.   Implement strStr() Easy Implement  strStr() . Given two strings  needle  and  haystack , return the index of the first occurrence of...