Join Regular Classroom : Visit ClassroomTech

Gupshup Overall Interview Questions + Coding Solutions – codewindow.in

Hot Topics

Gupshup Solution

Technical Round

Data structure and full multi-threading concept

Data structure is the organization of data in a computer to enable efficient access and modification. It involves the use of algorithms and data structures like arrays, linked lists, stacks, queues, trees, and graphs to store, manipulate, and retrieve data.
Multi-threading, on the other hand, is a programming concept that enables a program to run multiple threads concurrently. A thread is a lightweight process that can run independently of other threads within the same program. Multi-threading can be used to improve the performance and responsiveness of a program by allowing different tasks to be executed simultaneously.
In a multi-threaded program, each thread can access shared data structures and use them for processing. However, it’s essential to ensure that the threads don’t interfere with each other’s access to the shared data structures. This can be achieved by using synchronization techniques such as locks, semaphores, and monitors to coordinate the access to the shared data.
Additionally, when designing multi-threaded programs, it’s important to consider issues such as race conditions, deadlocks, and memory consistency, which can arise when multiple threads access and modify shared data structures concurrently.
In summary, data structures and multi-threading are closely related concepts in computer programming. Data structures provide the means to organize and store data, while multi-threading allows for efficient processing of that data in a concurrent manner.

String reverse

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

void reverse(string s){
    if(s.size()==0){
        return;
    }
    reverse(s.substr(1));
    cout<<s[0];
}

int main() {
    string s;
    cout<<"Enter the string you want to reverse: "<<endl;
    getline(cin,s);
    
    cout<<"Reversed string is:"<<endl;
    reverse(s);

    return 0;
}
/*
output:
Enter the string you want to reverse: hello
Reversed string is:
olleh
*/

Integer reverse

#include <iostream>
using namespace std;

int main() {
    int n,rem,rev=0;
    cout<<"Enter an integer "<<endl;
    cin>>n;
    
    while(n!=0){
        rem=n%10;
        rev=rev*10+rem;
        n=n/10;
    }

    cout<<"Reversed integer is: "<<rev<<endl;
    
    return 0;
}
/*
output:
Enter an integer 12356
Reversed integer is: 65321
*/

CSS alignment and media query

CSS (Cascading Style Sheets) alignment is the process of positioning HTML elements within the web page. CSS provides several alignment properties that control the positioning of elements relative to their parent container or the viewport. Some of the most commonly used alignment properties are:
  1. text-align: Specifies the horizontal alignment of text within an element. The values can be left, right, center, and justify.
  2. vertical-align: Specifies the vertical alignment of an inline-level element relative to its parent. The values can be top, bottom, middle, and baseline.
    1. float: Specifies the position of an element relative to its parent. The values can be left, right, and none.
    2. display: Specifies the display behavior of an element. The values can be block, inline, inline-block, none, etc.
    Media queries are a CSS feature that enables designers to apply different styles to a web page based on the characteristics of the display device. Media queries allow web designers to write CSS rules that only apply to specific screen sizes, resolutions, and orientation modes. For example, a media query can be used to apply specific styles to a web page when it is displayed on a mobile device with a smaller screen.
    Here is an example of a media query that changes the background color of a web page when the viewport width is less than 600 pixels:
@media (max-width: 600px) {
  body {
    background-color: lightblue;
  }
}
In this example, the @media rule specifies the condition for the styles to apply. The styles within the curly braces will only apply when the viewport width is less than 600 pixels. This allows web designers to create responsive designs that adapt to different screen sizes and orientations.

3 hat problem

The “Three Hat Problem” is a classic logic puzzle that involves determining the color of three hats given to three individuals. The individuals are lined up so that each can only see the hats in front of them but not the hat on their own head.
Here is a description of the problem:
There are three individuals standing in a line, each wearing a hat of either red or blue color. The individuals cannot see their own hats, but they can see the color of the hats worn by the people in front of them. The individuals are asked to guess the color of their hat. If they guess correctly, they get to keep the hat, otherwise, they lose it. The individuals can communicate with each other before they make their guesses.
The goal is to determine the color of each hat.
There are different approaches to solving this problem, but one possible solution is to have the first person guess a color, then have the second person guess the opposite color. If the first person’s guess is correct, then the third person will know their hat’s color. If the first person’s guess is wrong, then the second person’s guess will determine the color of both the first and third person’s hats.
This problem illustrates the importance of communication and the power of making educated guesses based on limited information. It’s a classic problem in logic and critical thinking, and it has been used as a test of problem-solving skills in several fields, including computer science and management.

Difference between DELETE and TRUNCATE.

DELETE
TRUNCATE
1.      It is a DML command
It is a DDL command
2.      If we want to delete rows from a table then we use this command.
We use this command to delete all the rows in a table at one go.
3.      We can rollback before commit.
We can’t rollback to previous log.
 

Problem on Kth largest element.

The problem of finding the kth largest element in a given collection of elements is a common problem in computer science and data structures. It involves finding the kth element in a sorted list of elements, with the largest element being the first element and the smallest element being the last element.
There are several algorithms that can be used to solve this problem, including:
  1. Sorting: One approach is to sort the elements in descending order and then return the kth element in the sorted list. This approach has a time complexity of O(n log n), where n is the number of elements.
    1. Heaps: Another approach is to use a max heap, which is a type of binary heap data structure that is optimized for finding the maximum element. The max heap can be used to efficiently find the kth largest element by keeping track of the k largest elements and discarding the rest. This approach has a time complexity of O(n log k).
    2. QuickSelect: QuickSelect is a variation of QuickSort, a popular sorting algorithm. It works by selecting a pivot element and partitioning the elements into two groups: those that are larger than the pivot and those that are smaller. QuickSelect then recursively searches the appropriate partition based on the value of k. This approach has an average time complexity of O(n).
    The choice of algorithm depends on the specific requirements of the problem and the trade-off between time and space complexity.

What is the reason behind the shape of a toothpaste cap?

The shape of a toothpaste cap is designed to serve several purposes, including:
  1. Ease of use: The shape of the toothpaste cap is designed to make it easy to open and close, even when wet. It should be simple to grip, even with soapy hands, and easy to twist or snap open and shut.
  2. Portion control: The shape of the toothpaste cap is also designed to control the amount of toothpaste dispensed. Many toothpaste caps have a screw-on design that allows for a precise amount of toothpaste to be dispensed with each turn, helping to prevent waste and ensuring that the toothpaste lasts longer.
  3. Aesthetics: The design of the toothpaste cap is also an important factor in the overall look and feel of the product. Toothpaste manufacturers may choose a particular shape or style of cap that appeals to their target market and complements the overall design of the packaging.
    1. Safety: The shape of the toothpaste cap is also important for safety reasons. Some toothpaste caps are designed to be child-resistant, making it more difficult for young children to access the toothpaste and potentially ingest it.
    Overall, the shape of a toothpaste cap is designed to balance ease of use, portion control, aesthetics, and safety, to ensure that the toothpaste is easy and convenient to use and that it provides maximum benefits to the user.

Problem on Maps which includes overriding of equals and hash code of class.

When working with Maps in Java, it is important to override the equals and hashCode methods of the class that is used as the key in the Map. This is because the Map uses the equals method to determine if two keys are equal, and the hashCode method to determine the index in the internal array where the value for a key is stored.
Here is an example of how to override the equals and hashCode methods in a class that is used as a key in a Map:
class Key {
  private int id;
  private String name;

  // Constructor and getters...

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    Key key = (Key) o;
    return id == key.id &&
           name.equals(key.name);
  }

  @Override
  public int hashCode() {
    return Objects.hash(id, name);
  }
}

Map<Key, Value> map = new HashMap<>();
map.put(new Key(1, "John"), new Value(100));
map.put(new Key(2, "Jane"), new Value(200));

Value value = map.get(new Key(1, "John"));
System.out.println(value.getAmount()); // 100
In this example, the Key class is used as the key in the Map, and it overrides the equals and hashCode methods to determine if two keys are equal based on their id and name values. The hashCode method is also implemented to ensure that keys with the same values produce the same hash code, so that they are stored in the same index in the Map’s internal array.
It’s important to note that when overriding the equals and hashCode methods, both methods should be overridden together, as the hashCode method is used by the Map to determine the index in the internal array, and the equals method is used to determine if two keys are equal. If the hashCode method is not overridden, or if it’s not implemented correctly, the Map may not work as expected, and it may not be able to find the correct value for a given key.

There is a round table and you and your friend are playing a coin game. One by one each has to place coin on the table, whosoever left last with no coin to place will lose. What should be the strategy?

The strategy to win this coin game is to always place an odd number of coins on the table.
Here’s why:
  1. When it’s your turn, place an odd number of coins on the table. This ensures that when it’s your friend’s turn, they will be left with an even number of coins, and they will have to place an even number of coins on the table.
  2. When it’s your friend’s turn, they will have to place an even number of coins on the table. This will leave an odd number of coins for you to place on the table on your next turn.
  3. Repeat this process of alternating odd and even numbers until there is only one coin left. The player who has to place the last coin loses.
By following this strategy, you will always have an odd number of coins left for you to place on the table, and your friend will always have an even number of coins, ensuring that you have the advantage in the game.

SQL Query Count, Where condition, Order by and join

Here’s an example of a SQL query that includes a count, a where condition, an order by clause, and a join:
SELECT COUNT(orders.order_id) AS total_orders, customers.name
FROM orders
JOIN customers ON orders.customer_id = customers.customer_id
WHERE orders.order_date >= ‘2022-01-01’
GROUP BY customers.name
ORDER BY total_orders DESC;
This query counts the number of orders (COUNT(orders.order_id)) for each customer (customers.name) that were placed on or after '2022-01-01' (WHERE orders.order_date >= '2022-01-01'). The results are grouped by customer name and ordered in descending order of the total number of orders (ORDER BY total_orders DESC). The join clause (JOIN customers ON orders.customer_id = customers.customer_id) is used to combine information from the orders and customers tables based on the customer_id field.
The query returns the total number of orders for each customer and the customer name. The result will be sorted by the total number of orders, with the customers who placed the most orders appearing first.

Find a particular element from a sorted array.

One common approach to finding a particular element in a sorted array is binary search.
Here’s the algorithm for binary search:
  1. Determine the middle index of the array.
  2. Compare the value at the middle index with the target element.
  3. If the value at the middle index is equal to the target element, return the index.
  4. If the value at the middle index is less than the target element, repeat the search in the upper half of the array (from the middle index to the end).
  5. If the value at the middle index is greater than the target element, repeat the search in the lower half of the array (from the start to the middle index).
  6. Repeat steps 1-5 until the target element is found or the search range is empty.
Here is an implementation of binary search in C++:
#include <iostream>
using namespace std;

int binarySearch(int arr[], int n, int target)
{
    int start = 0, end = n - 1;
    while (start <= end)
    {
        int mid = start + (end - start) / 2;
        if (arr[mid] == target)
            return mid;
        else if (arr[mid] < target)
            start = mid + 1;
        else
            end = mid - 1;
    }
    return -1;
}

int main()
{
    int arr[] = {1, 3, 4, 6, 7, 8, 9};
    int target = 6;
    int n = sizeof(arr) / sizeof(arr[0]);
    int result = binarySearch(arr, n, target);
    if (result == -1)
        cout << target << " is not present in the array" << endl;
    else
        cout << "The index of " << target << " is " << result << endl;
    return 0;
}
/*
output:
The index of 6 is 3
*/
This code performs a binary search on a sorted array arr with n elements to find the index of the target element target. If the target element is found, the index is returned; otherwise, -1 is returned, indicating that the target element is not present in the array.

Reverse the Linked List.

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

class Node{
    public:
    int data;
    Node* next;
    Node(int d){
        this->data=d;
        this->next=NULL;
    }
};

void insertAtTail(Node* &head, int val) {
    Node* n = new Node(val);
    
    if(head==NULL) {
        head=n;
        return;
    }
    
    Node* temp = head;
    while(temp->next!=NULL) {
        temp=temp->next;
    }
    temp->next = n;
}

void print(Node* &head) {
    Node* temp = head;
    while(temp != NULL ) {
        cout << temp -> data << " ";
        temp = temp -> next;
    }
    cout << endl;
}

void reverse(Node* &head) {
    if(head==NULL) {
        return;
    }
    reverse(head->next);
    
    cout<<head->data<<" ";
}

int main() {
    
    Node* node = new Node(10);
    Node* head = node;
    
    insertAtTail(head,20);
    insertAtTail(head,30);
    insertAtTail(head,40);
    
    print(head);
    reverse(head);
    return 0;
}
/*
output:
10 20 30 40 
40 30 20 10 
*/

How to create thread-safe singleton in Java using double checked locking?

Here’s an example of how to create a thread-safe singleton in Java using double-checked locking:
public class Singleton {
    private static volatile Singleton instance;

    private Singleton() {}

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}
In this example, the singleton instance is created only if it has not already been created, and this check is done using a double-checked locking pattern. The volatile keyword ensures that the instance is created only once, even if multiple threads are executing the getInstance method simultaneously.
The first if statement checks whether the instance has already been created. If it has not, the synchronized block is entered to create the instance. Within the synchronized block, another if statement is used to double-check that the instance has not been created by another thread while the current thread was waiting to enter the synchronized block.
This approach ensures that the singleton instance is created only once, even in a multi-threaded environment, while also minimizing the overhead of synchronization.

Nagarro Solved

Automata Fixing

      

We Love to Support you

Go through our study material. Your Job is awaiting.

Recent Posts
Categories