Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Infosys Coding Questions and Answers

Last Updated on February 20, 2023 by Prepbytes

There are many reasons that drive one candidate to join Infosys such as career stability, better working conditions, competitive salary, Global experience, innovation, social responsibility, and diversity. But one cannot get placed in Infosys directly he has to follow the interview process in that there are various interview rounds and he has to clear each interview round to get placed in Infosys.
Among all the interview rounds there are many topics or domains that are covered or tested like aptitude, technical knowledge, and coding questions. In this blog, we will discuss some of the coding questions that are asked in Infosys.

Infosys Coding Questions

Here is the list of some of the commonly asked Infosys Coding Questions.

1. Write a program in C++ to quickly swap two arrays.

Sample Input

a[] = {11, 12,13,14}
b[] = {15, 16, 17, 18}

Sample Output

a[] = {15, 16, 17, 18}
b[] = {11, 12, 13, 14}
// Illustrating the use of swap function
// to swap two arrays
#include <iostream>
#include <utility>
using namespace std;

int main ()
{
    int a[] = {11, 12, 13, 14};
    int b[] = {15, 16, 17, 18};
    int n = sizeof(a)/sizeof(a[0]);

    swap(a, b);

    cout << "a[] = ";
    for (int i=0; i<n; i++)
        cout << a[i] << ", ";

    cout << "\nb[] = ";
    for (int i=0; i<n; i++)
        cout << b[i] << ", ";

    return 0;
}

Output

a[] = 15, 16, 17, 18, 
b[] = 11, 12, 13, 14,

2. Write a Program to sort a string of characters

Sample Input

s=”prepbytes”

Sample Output

s=”beepprsty”
#include<bits/stdc++.h>
using namespace std;

const int MAX_CHAR = 26;

void sortString(string &str)
{
    
    int charCount[MAX_CHAR] = {0};
    
    for (int i=0; i<str.length(); i++)

    
        charCount[str[i]-'a']++;
    
    for (int i=0;i<MAX_CHAR;i++)
        for (int j=0;j<charCount[i];j++)
            cout << (char)('a'+i);
}

int main()
{
    string s = "prepbytes";
    sortString(s);
    return 0;
}
 class SortString{
    static final int MAX_CHAR = 26;

    static void sortString(String str) {

        int letters[] = new int[MAX_CHAR];

    
        for (char x : str.toCharArray()) {

    
            letters[x - 'a']++;
        }

    
        for (int i = 0; i < MAX_CHAR; i++) {
            for (int j = 0; j < letters[i]; j++) {
                System.out.print((char) (i + 'a'));
            }
        }
    }

    public static void main(String[] args) {
        sortString("prepbytes");
    }
}
MAX_CHAR = 26

def sortString(str):
    

    charCount = [0 for i in range(MAX_CHAR)]
    
    
    for i in range(0, len(str), 1):
        
    
        charCount[ord(str[i]) - ord('a')] += 1
    

    for i in range(0, MAX_CHAR, 1):
        for j in range(0, charCount[i], 1):
            print(chr(ord('a') + i), end = "")

if __name__ == '__main__':
    s = "prepbytes"
    sortString(s)
    

Output

beepprsty

3. Write a program to count the number of unique characters in a given string.

Sample Input

s=”prepbytes”

Sample Output

7
#include <bits/stdc++.h>
using namespace std;

int cntDistinct(string str)
{

    unordered_set<char> s;

    for (int i = 0; i < str.size(); i++) {

        
        s.insert(str[i]);
    }

    return s.size();
}

int main()
{
    string str = "prepbytes";
    cout << cntDistinct(str);

    return 0;
}
import java.util.*;

class Prepbytes{


static int cntDistinct(String str)
{
    

    HashSet<Character> s = new HashSet<Character>();

    for(int i = 0; i < str.length(); i++)
    {
        
    
        s.add(str.charAt(i));
    }

    return s.size();
}

public static void main(String args[])
{
    String str = "prepbytes";
    System.out.print(cntDistinct(str));
}
}

def cntDistinct(st):

    s = set([])

    for i in range(len(st)):


        s.add(st[i])

    return len(s)

if __name__ == "__main__":

    st = "prepbytes"
    print(cntDistinct(st))

Output

7

4. Write a program to multiply two matrices and print the result through another matrix.

Sample Input

m1[m][n] = { {1, 1}, {2, 2} }
m2[n][p] = { {1, 1}, {2, 2} }

Sample Output

result[m][p] = { {3, 3}, {6, 6} }
#include <bits/stdc++.h>
using namespace std;


#define R1 2 
#define C1 2 
#define R2 2 
#define C2 2 

void mulMat(int mat1[][C1], int mat2[][C2])
{
    int rslt[R1][C2];

    cout << "Multiplication of given two matrices is:\n";

    for (int i = 0; i < R1; i++) {
        for (int j = 0; j < C2; j++) {
            rslt[i][j] = 0;

            for (int k = 0; k < R2; k++) {
                rslt[i][j] += mat1[i][k] * mat2[k][j];
            }

            cout << rslt[i][j] << "\t";
        }

        cout << endl;
    }
}

int main()
{
    int mat1[R1][C1] = { { 4, 4 },
                        { 5, 3 } };

    int mat2[R2][C2] = { { 4, 7 },
                        { 6, 2 } };

    if (C1 != R2) {
        cout << "The number of columns in Matrix-1 must "
                "be equal to the number of rows in "
                "Matrix-2"
            << endl;
        cout << "Please update MACROs according to your "
                "array dimension in #define section"
            << endl;

        exit(EXIT_FAILURE);
    }

    mulMat(mat1, mat2);

    return 0;
}

import java.io.*;
import java.util.*;

class Prepbytes {

    static int R1 = 2; 
    static int C1 = 2;  
    static int R2 = 2;  
    static int C2 = 2;  

    
    static void mulMat(int[][] mat1, int[][] mat2)
    {
        
        int[][] rslt = new int[R1][C2];
        System.out.println(
            "Multiplication of given two matrices is:");
        int i, j, k;
        for (i = 0; i < R1; i++) {
            for (j = 0; j < C2; j++) {
                rslt[i][j] = 0;
                for (k = 0; k < R2; k++)
                    rslt[i][j] += mat1[i][k] * mat2[k][j];
                System.out.print(rslt[i][j] + " ");
            }
            System.out.println("");
        }
    }

    public static void main(String[] args)
    {
        int[][] mat1 = { { 4, 4 },
                        { 5, 3 } };

        int[][] mat2 = { { 4, 7 },
                        { 6, 2 } };


        if (C1 != R2) {
            System.out.println(
                "The number of columns in Matrix-1 must be equal to the number of rows in Matrix-2");
            System.out.println(
                "Please update the global variables according to your array dimension");
        }
        else {
        
            mulMat(mat1, mat2);
        }
    }
}
def mulMat(mat1, mat2, R1, R2, C1, C2):
    rslt = [[0, 0, 0, 0],
            [0, 0, 0, 0],
            [0, 0, 0, 0],
            [0, 0, 0, 0]]

    for i in range(0, R1):
        for j in range(0, C2):
            for k in range(0, R2):
                rslt[i][j] += mat1[i][k] * mat2[k][j]

    print("Multiplication of given two matrices is:")
    for i in range(0, R1):
        for j in range(0, C2):
            print(rslt[i][j], end=" ")
        print("\n", end="")


if __name__ == '__main__':
    R1 = 2
    R2 = 2
    C1 = 2
    C2 = 2
    
    mat1 = [[4, 4],
        [5, 3]]
    

    mat2 = [[4, 7],
        [6, 2]]

    if C1 != R2:
        print("The number of columns in Matrix-1 must be equal to the number of rows in " + "Matrix-2", end='')
        print("\n", end='')
        print("Please update MACROs according to your array dimension in #define section", end='')
        print("\n", end='')
    else:
        mulMat(mat1, mat2, R1, R2, C1, C2)

Output

Multiplication of given two matrices is:
40 36 
38 41

5. Given a string find the next permutation of the given string in C++.

Sample Input

s=”dcd”

Sample Output

s=”ddc”
#include <iostream>

using namespace std;

void swap(char* a, char* b)
{
    if (*a == *b)
        return;
    *a ^= *b;
    *b ^= *a;
    *a ^= *b;
}
void rev(string& s, int l, int r)
{
    while (l < r)
        swap(&s[l++], &s[r--]);
}

int bsearch(string& s, int l, int r, int key)
{
    int index = -1;
    while (l <= r) {
        int mid = l + (r - l) / 2;
        if (s[mid] <= key)
            r = mid - 1;
        else {
            l = mid + 1;
            if (index == -1 || s[index] >= s[mid])
                index = mid;
        }
    }
    return index;
}

bool nextpermutation(string& s)
{
    int len = s.length(), i = len - 2;
    while (i >= 0 && s[i] >= s[i + 1])
        --i;
    if (i < 0)
        return false;
    else {
        int index = bsearch(s, i + 1, len - 1, s[i]);
        swap(&s[i], &s[index]);
        rev(s, i + 1, len - 1);
        return true;
    }
}

int main()
{
    string s = { "prepbytes" };
    bool val = nextpermutation(s);
    if (val == false)
        cout << "No Word Possible" << endl;
    else
        cout << s << endl;
    return 0;
}

Output

prepbytse

6. Write a program to find the area of the incircle of a right angles triangle.

Sample Input

P = 5, B = 12, H = 13 

Sample Output

12.56 
#include <bits/stdc++.h>
using namespace std;
#define PI 3.14159265

float area_inscribed(float P, float B, float H)
{
    return ((P + B - H) * (P + B - H) * (PI / 4));
}


int main()
{
    float P = 3, B = 4, H = 5;
    cout << area_inscribed(P, B, H) << endl;

    return 0;
}

import java.lang.*;

class Prepbytes {

    static double PI = 3.14159265;

    public static double area_inscribed(double P, double B,
                                        double H)
    {
        return ((P + B - H) * (P + B - H) * (PI / 4));
    }

    public static void main(String[] args)
    {
        double P = 3, B = 4, H = 5;
        System.out.println(area_inscribed(P, B, H));
    }
}
PI = 3.14159265

def area_inscribed(P, B, H):
    return ((P + B - H)*(P + B - H)*(PI / 4))

P = 3
B = 4
H = 5
print(area_inscribed(P, B, H))

7. Write a program that will find the missing characters that are needed to make the string a panagram.

Sample Input

welcome to prepbytes

Sample Output

adfghijknquvxz
#include<bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 26;


string missingChars(string str)
{
    bool present[MAX_CHAR] = {false};

    for (int i=0; i<str.length(); i++)
    {
        if (str[i] >= 'a' && str[i] <= 'z')
            present[str[i]-'a'] = true;
        else if (str[i] >= 'A' && str[i] <= 'Z')
            present[str[i]-'A'] = true;
    }

    string res = "";
    for (int i=0; i<MAX_CHAR; i++)
        if (present[i] == false)
            res.push_back((char)(i+'a'));

    return res;
}

int main()
{
    string str = "Welcome to prepbytes";
    cout << missingChars(str);
    return 0;
}	
import java.io.*;
import java.util.ArrayList;

class Prepbytes{
    
private static ArrayList<Character>missingChars(
    String str, int strLength)
{
    final int MAX_CHARS = 26;
    

    boolean[] present = new boolean[MAX_CHARS];
    ArrayList<Character> charsList = new ArrayList<>();
    

    for(int i = 0; i < strLength; i++)
    {
        if ('A' <= str.charAt(i) &&
                str.charAt(i) <= 'Z')
            present[str.charAt(i) - 'A'] = true;
        else if ('a' <= str.charAt(i) &&
                        str.charAt(i) <= 'z')
            present[str.charAt(i) - 'a'] = true;
    }
    
    
    for(int i = 0; i < MAX_CHARS; i++)
    {
        if (present[i] == false)
            charsList.add((char)(i + 'a'));
    }
    return charsList;
}

public static void main(String[] args)
{
    String str = "Welcome to prepbytes";
                
    ArrayList<Character> missing = Prepbytes.missingChars(
        str, str.length());
        
    if (missing.size() >= 1)
    {
        for(Character character : missing)
        {
            System.out.print(character);
        }
    }
}
}

MAX_CHAR = 26


def missingChars(Str):
    

    present = [False for i in range(MAX_CHAR)]


    for i in range(len(Str)):
        if (Str[i] >= 'a' and Str[i] <= 'z'):
            present[ord(Str[i]) - ord('a')] = True
        elif (Str[i] >= 'A' and Str[i] <= 'Z'):
            present[ord(Str[i]) - ord('A')] = True


    res = ""

    for i in range(MAX_CHAR):
        if (present[i] == False):
            res += chr(i + ord('a'))
            
    return res

Str = "Welcome to prepbytes"

print(missingChars(Str))

Output

adfghijknquvxz

8. Write a program that converts the given temperature of Fahrenheit into celsius.

Sample Input

0

Sample Output

32
#include <bits/stdc++.h>
using namespace std;

float Cel_To_Fah(float N)
{
    return ((N * 9.0 / 5.0) + 32.0);
}

int main()
{
    float N = 40.0;

    cout << Cel_To_Fah(N);
    return 0;
}
class Prepbytes {


    static float Cel_To_Fah(float N)
    {
        return ((N * 9.0f / 5.0f) + 32.0f);
    }

    public static void main(String[] args)
    {
        float N = 40.0f;
    
        System.out.println(Cel_To_Fah(N));
    }
}

def Cel_To_Fah(n):

    return (n*1.8)+32



n = 40

print(int(Cel_To_Fah(n)))

Output

104

9. Write a program that will find the sum of all the prime numbers between 1 and N.

Sample Input

10

Sample Output

17
#include <bits/stdc++.h>
using namespace std;

int sumOfPrimes(int n)
{
    bool prime[n + 1];


    memset(prime, true, n + 1);

    for (int p = 2; p * p <= n; p++) {

        
        if (prime[p] == true) {

            for (int i = p * 2; i <= n; i += p)
                prime[i] = false;
        }
    }

    int sum = 0;
    for (int i = 2; i <= n; i++)
        if (prime[i])
            sum += i;
    return sum;
}

int main()
{
    int n = 15;
    cout << sumOfPrimes(n);
    return 0;
}
import java.io.*;
import java.util.*;

class Prepbytes {
    

    static int sumOfPrimes(int n)
    {
        boolean prime[]=new boolean[n + 1];
    
        Arrays.fill(prime, true);
    
        for (int p = 2; p * p <= n; p++) {
    
            
            if (prime[p] == true) {
    
                for (int i = p * 2; i <= n; i += p)
                    prime[i] = false;
            }
        }
    
        
        int sum = 0;
        for (int i = 2; i <= n; i++)
            if (prime[i])
                sum += i;
        return sum;
    }

    public static void main(String args[])
    {
        int n = 15;
        System.out.print(sumOfPrimes(n));
    }
}

def sumOfPrimes(n):
    prime = [True] * (n + 1)

    
    p = 2
    while p * p <= n:
        if prime[p] == True:
            i = p * 2
            while i <= n:
                prime[i] = False
                i += p
        p += 1
        

    sum = 0
    for i in range (2, n + 1):
        if(prime[i]):
            sum += i
    return sum

n = 15
print(sumOfPrimes(n))

Output

41

10. Write a program to make the largest number from the digits of the array.

Sample Input

{1, 34, 3, 98, 9, 76, 45, 4}

Sample Output

998764543431
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int myCompare(string X, string Y)
{
    string XY = X.append(Y);


    string YX = Y.append(X);


    return XY.compare(YX) > 0 ? 1 : 0;
}


void printLargest(vector<string> arr)
{
    

    sort(arr.begin(), arr.end(), myCompare);

    for (int i = 0; i < arr.size(); i++)
        cout << arr[i];
}

int main()
{
    vector<string> arr;

    arr.push_back("54");
    arr.push_back("546");
    arr.push_back("548");
    arr.push_back("60");
    printLargest(arr);

    return 0;
}
import java.util.*;

class Prepbytes {

    
    static void printLargest(Vector<String> arr)
    {

        Collections.sort(arr, new Comparator<String>()
        {
    
            @Override public int compare(String X, String Y)
            {

                String XY = X + Y;

                String YX = Y + X;

                
                return XY.compareTo(YX) > 0 ? -1 : 1;
            }
        });

        Iterator it = arr.iterator();

        while (it.hasNext())
            System.out.print(it.next());
    }

    public static void main(String[] args)
    {

        Vector<String> arr;
        arr = new Vector<>();

        arr.add("54");
        arr.add("546");
        arr.add("548");
        arr.add("60");
        printLargest(arr);
    }
}
def largestNumber(array):

    if len(array)==1:
        return str(array[0])
    for i in range(len(array)):
        array[i]=str(array[i])
    for i in range(len(array)):
        for j in range(1+i,len(array)):
            if array[j]+array[i]>array[i]+array[j]:
                array[i],array[j]=array[j],array[i]

    result=''.join(array)
    if(result=='0'*len(result)):
        return '0'
    else:
        return result
        
        
    a = [54, 546, 548, 60]
    print(largestNumber(a))

Output

6054854654

11. Given an array form a triangle such that the last row of the triangle contains all the elements of the array and the row above it will contain the sum of two elements below it.

Sample Input

arr[] = {4, 7, 3, 6, 7};

Sample Output

81
40 41
21 19 22
11 10 9 13
4 7 3 6 7
#include <bits/stdc++.h>
using namespace std;

void printTriangle(int arr[], int n)
{
    int tri[n][n];
    memset(tri, 0, sizeof(tri));

    for (int i = 0; i < n ; i++)
        tri[n-1][i] = arr[i];

    for (int i = n-2; i >=0; i--)
    for (int j = 0; j <= i; j++)
        tri[i][j] = tri[i+1][j] + tri[i+1][j+1];

    for (int i = 0; i < n; i++)
    {
        for(int j = 0; j <= i ; j++)
            cout << tri[i][j]<<" ";
        cout << endl;
    }
}

int main()
{
    int arr[] = {4, 7, 3, 6, 7, 3};
    int n = sizeof(arr)/sizeof(arr[0]);
    printTriangle(arr, n);
    return 0;
}
class Test{
    
    static int arr[] = new int[]{4, 7, 3, 6, 7, 3};
    
    public static void printTriangle(int n)
    {
        int tri[][] = new int[n][n];
        
        for (int i = 0; i < n ; i++)
            tri[n-1][i] = arr[i];
        
        for (int i = n-2; i >=0; i--)
            for (int j = 0; j <= i; j++)
            tri[i][j] = tri[i+1][j] + tri[i+1][j+1];
        
        for (int i = 0; i < n; i++)
        {
            for(int j = 0; j <= i ; j++)
                System.out.print(tri[i][j] + " ");
            System.out.println();
        }
    }
    
    public static void main(String[] args)
    {
        printTriangle(arr.length);
        }
}
def printTriangle(arr, n):
    
    tri = [[0 for i in range(n)]
            for i in range(n)]

    for i in range(n):
        tri[n - 1][i] = arr[i]

    i = n - 2
    while(i >= 0):
        for j in range(0, i + 1, 1):
            tri[i][j] = (tri[i + 1][j] +
                        tri[i + 1][j + 1])
            
        i -= 1

    for i in range(0, n, 1):
        for j in range(0, i + 1, 1):
            print(tri[i][j], end = " ")
        print("\n", end = "")

    arr = [4, 7, 3, 6, 7, 3]
    n = len(arr)
    printTriangle(arr, n)
    

Output

167 
81 86 
40 41 45 
21 19 22 23 
11 10 9 13 10 
4 7 3 6 7 3

12. Given the price of the stock on each day find the maximum profit you can earn by selling them.

Sample Input

arr[] = {100, 180, 260, 310, 40, 535, 695}

Sample Output

865
#include <bits/stdc++.h>
using namespace std;


int maxProfit(int price[], int start, int end)
{

    
    if (end <= start)
        return 0;

    int profit = 0;


    for (int i = start; i < end; i++) {

        for (int j = i + 1; j <= end; j++) {

        
            if (price[j] > price[i]) {

                int curr_profit
                    = price[j] - price[i]
                    + maxProfit(price, start, i - 1)
                    + maxProfit(price, j + 1, end);

                profit = max(profit, curr_profit);
            }
        }
    }
    return profit;
}

int main()
{
    int price[] = { 100, 180, 260, 310, 40, 535, 695 };
    int n = sizeof(price) / sizeof(price[0]);

    cout << maxProfit(price, 0, n - 1);

    return 0;
}
import java.util.*;

class PrepBytes {

    
    static int maxProfit(int price[], int start, int end)
    {

    
        if (end <= start)
            return 0;

        int profit = 0;

        for (int i = start; i < end; i++) {

            for (int j = i + 1; j <= end; j++) {

                if (price[j] > price[i]) {

                    int curr_profit
                        = price[j] - price[i]
                        + maxProfit(price, start, i - 1)
                        + maxProfit(price, j + 1, end);

                    profit = Math.max(profit, curr_profit);
                }
            }
        }
        return profit;
    }

    public static void main(String[] args)
    {
        int price[] = { 100, 180, 260, 310, 40, 535, 695 };
        int n = price.length;

        System.out.print(maxProfit(price, 0, n - 1));
    }
}

def maxProfit(price, start, end):

    if (end <= start):
        return 0

    profit = 0


    for i in range(start, end, 1):

        for j in range(i+1, end+1):

            if (price[j] > price[i]):

                curr_profit = price[j] - price[i] +\
                    maxProfit(price, start, i - 1) + \
                    maxProfit(price, j + 1, end)

                profit = max(profit, curr_profit)

    return profit


if __name__ == '__main__':
    price = [100, 180, 260, 310, 40, 535, 695]
    n = len(price)

    print(maxProfit(price, 0, n - 1))

Output

865

13. You are given a matrix that contains only 0 and 1 find the maximum size of a rectangle that contains only 1.

Sample Input

0 1 1 0
1 1 1 1
1 1 1 1
1 1 0 0

Sample Output

8
#include <bits/stdc++.h>
using namespace std;

#define R 4
#define C 4




int maxHist(int row[])
{
    
    stack<int> result;

    int top_val; 

    int max_area = 0; 


    int area = 0;

    int i = 0;
    while (i < C) {
        
        if (result.empty() || row[result.top()] <= row[i])
            result.push(i++);

        else {
        
            top_val = row[result.top()];
            result.pop();
            area = top_val * i;

            if (!result.empty())
                area = top_val * (i - result.top() - 1);
            max_area = max(area, max_area);
        }
    }


    while (!result.empty()) {
        top_val = row[result.top()];
        result.pop();
        area = top_val * i;
        if (!result.empty())
            area = top_val * (i - result.top() - 1);

        max_area = max(area, max_area);
    }
    return max_area;
}


int maxRectangle(int A[][C])
{

    int result = maxHist(A[0]);

    for (int i = 1; i < R; i++) {

        for (int j = 0; j < C; j++)

            if (A[i][j])
                A[i][j] += A[i - 1][j];


        result = max(result, maxHist(A[i]));
    }

    return result;
}

int main()
{
    int A[][C] = {
        { 0, 1, 1, 0 },
        { 1, 1, 1, 1 },
        { 1, 1, 1, 1 },
        { 1, 1, 0, 0 },
    };

    cout << "Area of maximum rectangle is "
        << maxRectangle(A);

    return 0;
}
import java.io.*;
import java.util.*;

class PrepBytes {


    static int maxHist(int R, int C, int row[])
    {
    
        Stack<Integer> result = new Stack<Integer>();

        int top_val;

        int max_area = 0; 

        int area = 0; 

    
        int i = 0;
        while (i < C) {
            
            if (result.empty()
                || row[result.peek()] <= row[i])
                result.push(i++);

            else {
            
                top_val = row[result.peek()];
                result.pop();
                area = top_val * i;

                if (!result.empty())
                    area
                        = top_val * (i - result.peek() - 1);
                max_area = Math.max(area, max_area);
            }
        }

    
        while (!result.empty()) {
            top_val = row[result.peek()];
            result.pop();
            area = top_val * i;
            if (!result.empty())
                area = top_val * (i - result.peek() - 1);

            max_area = Math.max(area, max_area);
        }
        return max_area;
    }

    
    static int maxRectangle(int R, int C, int A[][])
    {
    
        int result = maxHist(R, C, A[0]);


        for (int i = 1; i < R; i++) {

            for (int j = 0; j < C; j++)

                if (A[i][j] == 1)
                    A[i][j] += A[i - 1][j];

        
            result = Math.max(result, maxHist(R, C, A[i]));
        }

        return result;
    }


    public static void main(String[] args)
    {
        int R = 4;
        int C = 4;

        int A[][] = {
            { 0, 1, 1, 0 },
            { 1, 1, 1, 1 },
            { 1, 1, 1, 1 },
            { 1, 1, 0, 0 },
        };
        System.out.print("Area of maximum rectangle is "
                        + maxRectangle(R, C, A));
    }
}

class Solution():
    def maxHist(self, row):
    
        result = []

        # Top of stack
        top_val = 0

        max_area = 0

        area = 0 

    
        i = 0
        while (i < len(row)):

        
            if (len(result) == 0) or (row[result[-1]] <= row[i]):
                result.append(i)
                i += 1
            else:

            
                top_val = row[result.pop()]
                area = top_val * i

                if (len(result)):
                    area = top_val * (i - result[-1] - 1)
                max_area = max(area, max_area)

        
        while (len(result)):
            top_val = row[result.pop()]
            area = top_val * i
            if (len(result)):
                area = top_val * (i - result[-1] - 1)

            max_area = max(area, max_area)

        return max_area


    def maxRectangle(self, A):

        
        result = self.maxHist(A[0])


        for i in range(1, len(A)):

            for j in range(len(A[i])):

                
                if (A[i][j]):
                    A[i][j] += A[i - 1][j]

            result = max(result, self.maxHist(A[i]))

        return result


if __name__ == '__main__':
    A = [[0, 1, 1, 0],
        [1, 1, 1, 1],
        [1, 1, 1, 1],
        [1, 1, 0, 0]]
    ans = Solution()

    print("Area of maximum rectangle is",
        ans.maxRectangle(A))

Output

Area of maximum rectangle is 8

14. Given the coordinates of the endpoints of two rectangles find whether they overlap each other or not.

#include <bits/stdc++.h>

struct Point {
    int x, y;
};


bool doOverlap(Point l1, Point r1, Point l2, Point r2)
{
    if (l1.x == r1.x || l1.y == r1.y || r2.x == l2.x || l2.y == r2.y)
        return false;

    if (l1.x > r2.x || l2.x > r1.x)
        return false;

    if (r1.y > l2.y || r2.y > l1.y)
        return false;

    return true;
}

int main()
{
    Point l1 = { 0, 10 }, r1 = { 10, 0 };
    Point l2 = { 5, 5 }, r2 = { 15, 0 };
    if (doOverlap(l1, r1, l2, r2))
        printf("Rectangles Overlap");
    else
        printf("Rectangles Don't Overlap");
    return 0;
}
class PrepBytes {

static class Point {

        int x, y;
    }

static boolean doOverlap(Point l1, Point r1, Point l2, Point r2) {
        if (l1.x == r1.x || l1.y == r1.y || r2.x == l2.x || l2.y == r2.y)
            return false;
    
        if (l1.x > r2.x || l2.x > r1.x) {
            return false;
        }

        if (r1.y > l2.y || r2.y > l1.y) {
            return false;
        }

        return true;
    }

    public static void main(String[] args) {
        Point l1 = new Point(),r1 = new Point(),
                l2 = new Point(),r2 = new Point();
        l1.x=0;l1.y=10; r1.x=10;r1.y=0;
        l2.x=5;l2.y=5; r2.x=15;r2.y=0;

        if (doOverlap(l1, r1, l2, r2)) {
            System.out.println("Rectangles Overlap");
        } else {
            System.out.println("Rectangles Don't Overlap");
        }
    }
}
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

def do_overlap(l1, r1, l2, r2):
    
    if l1.x == r1.x or l1.y == r1.y or r2.x == l2.x or l2.y == r2.y:
        return False
    
    if l1.x > r2.x or l2.x > r1.x:
        return False

    if r1.y > l2.y or r2.y > l1.y:
        return False

    return True

if __name__ == "__main__":
    l1 = Point(0, 10)
    r1 = Point(10, 0)
    l2 = Point(5, 5)
    r2 = Point(15, 0)

    if(do_overlap(l1, r1, l2, r2)):
        print("Rectangles Overlap")
    else:
        print("Rectangles Don't Overlap")

Output

Rectangles Overlap

15. You are given two strings to find whether we can convert one string to another by rotating in two places.

Sample Input

string1 = “amazon”, string2 = “azonam” 

Sample Output

Yes
#include<bits/stdc++.h>
using namespace std;

bool isRotated(string str1, string str2)
{
    if (str1.length() != str2.length())
        return false;
    if(str1.length()<2){
    return str1.compare(str2) == 0;
    }
    string clock_rot = "";
    string anticlock_rot = "";
    int len = str2.length();

    anticlock_rot = anticlock_rot +
                    str2.substr(len-2, 2) +
                    str2.substr(0, len-2) ;

    clock_rot = clock_rot +
                str2.substr(2) +
                str2.substr(0, 2) ;

    return (str1.compare(clock_rot) == 0 ||
            str1.compare(anticlock_rot) == 0);
}

int main()
{
    string str1 =  "prep";
    string str2 =  " eppr";

    isRotated(str1, str2) ? cout << "Yes"
                        : cout << "No";
    return 0;
}
class Test
{

    static boolean isRotated(String str1, String str2)
    {
        if (str1.length() != str2.length())
            return false;
        if(str1.length() < 2)
        {
            return str1.equals(str2);
        }
    
        String clock_rot = "";
        String anticlock_rot = "";
        int len = str2.length();
    
        anticlock_rot = anticlock_rot +
                        str2.substring(len-2, len) +
                        str2.substring(0, len-2) ;
    
        clock_rot = clock_rot +
                    str2.substring(2) +
                    str2.substring(0, 2) ;
    
        return (str1.equals(clock_rot) ||
                str1.equals(anticlock_rot));
    }
    
    public static void main(String[] args)
    {
        String str1 =  "prep";
    String str2 =  " eppr";
    
        System.out.println(isRotated(str1, str2) ? "Yes"
                            : "No");
    }
}
def isRotated(str1, str2):

    if (len(str1) != len(str2)):
        return False
    
    if(len(str1) < 2):
        return str1 == str2
    clock_rot = ""
    anticlock_rot = ""
    l = len(str2)

    anticlock_rot = (anticlock_rot + str2[l - 2:] +
                                    str2[0: l - 2])
    
    clock_rot = clock_rot + str2[2:] + str2[0:2]

    return (str1 == clock_rot or
            str1 == anticlock_rot)


str1 = "prep"
str2 = "eppr"
if isRotated(str1, str2):
    print("Yes")
else:
    print("No")

Output

No

Frequently Asked Questions

1. How many coding questions come in Infosys Exam?
In the Infosys exam, there are three coding questions and they are of different difficulties which you have to attempt within 3 hours.

2. Are the questions which have come in previous years papers will repeat again?
There is a very low probability of repeating the same questions but the concept can be repeated and can be molded into a different question.

3. Is the exam taken offline or online mode?
The exam is taken online mode.

4. Name 3 Programming languages that are allowed in Infosys.
The three languages are:

  • C++
  • Java
  • Python

Leave a Reply

Your email address will not be published. Required fields are marked *