Delhivery Interview Preparation and Recruitment Process


About Delhivery:


Delhivery Limited is India’s largest fully integrated logistics and supply chain services company, headquartered in Gurugram, Haryana. Founded in 2011 by Sahil Barua, Kapil Bharati, Mohit Tandon, Suraj Saharan, and Bhavesh Manglani, it initially started as a hyperlocal delivery service for offline stores but pivoted to focus on e-commerce logistics. The company provides a wide range of services, including express parcel delivery, warehousing, freight (part truckload and full truckload), cross-border shipping, supply chain solutions, and value-added services like payment collection, reverse logistics, and fraud detection. Its mission is to build the operating system for commerce in India through world-class infrastructure, high-quality logistics, and cutting-edge technology.

Delhivery Interview Preparation


Key Details:


* Founders:
Sahil Barua (CEO), Kapil Bharati (CTO), Mohit Tandon, Suraj Saharan, and Bhavesh Manglani. Tandon and Manglani left the company in March 2021.

* Services: Express parcel, heavy goods delivery, warehousing, cross-border logistics, supply chain software, last-mile delivery, and rapid commerce (30-minute to 2-hour deliveries).

* Reach: Operates in over 2,000 cities in India, servicing 220+ countries, with a network covering 19,990+ sq ft of warehouse space and 1,400+ serviceable pin codes.

* Technology: Utilizes proprietary network design and engineering for faster, cost-efficient deliveries, with tools like real-time tracking, NDR management, and WhatsApp-based updates.

* Clients: Serves e-commerce giants (e.g., Flipkart, Amazon), D2C brands, small businesses, and individuals.


Financials and Funding:


* Public Company: Listed on BSE and NSE since its IPO in May 2022, raising ₹5,235 crore at a valuation of ₹35,283 crore (US$4.1 billion).

* Funding: Raised $1.25 billion over 12 rounds from investors like SoftBank, Fidelity, Nexus Venture Partners, and Carlyle. Valued at $3.41 billion as of 2024.

* Revenue: ₹8,816 crore in FY24, with a market cap of ₹20,735 crore. Profit was ₹21.1 crore, though it has faced challenges with low return on equity (-11% over 3 years).

* Acquisitions: Acquired Ecom Express for ₹1,407 crore (2025), Spoton Logistics (2021), and Transition Robotics (2021).


Recent Developments:


*
Ecom Express Acquisition: In April 2025, Delhivery acquired a 99.4% stake in Ecom Express for ₹1,400 crore to expand its logistics footprint and improve margins amid muted growth in its core e-commerce parcel business.

* Rapid Commerce: Launched services enabling 30-minute to 2-hour deliveries for D2C brands, with Milind Sharma appointed to lead this segment.

* Recognition: Named the Most Preferred Third-Party Logistics (3PL) Partner for D2C brands in India for two consecutive years (2024–2025) by Redseer Strategy Consultants.


Challenges:


* Market Competition: Faces competition from XpressBees, Shadowfax, and ClickPost in a highly competitive logistics market.

* Stock Performance: Trading below its IPO price, impacted by macroeconomic factors and company-specific issues.

* Employee Feedback: Rated 3.9/5 on AmbitionBox, with praise for work culture but criticism for limited training and overtime demands.


Vision and Impact:


Delhivery aims to shrink time and distance, making commerce seamless across India and globally. It has handled over 450 million transactions since inception and is a backbone for India’s $160 billion logistics industry, which is projected to grow to $215 billion in two years. Its focus on technology and scalability has made it a critical enabler for e-commerce and D2C brands.

For more details, visit Delhivery’s official website (https://www.delhivery.com) or investor relations page (https://www.delhivery.com/investor-relations).



Delhivery Recruitment Process


Delhivery’s recruitment process varies by role (e.g., technical, operations, delivery personnel, or managerial) and whether the candidate is a fresher, experienced professional, or applying via campus/off-campus drives. Below is an overview of the recruitment process based on available information, particularly for technical roles like software developers and general entry-level positions.

General Recruitment Process

Delhivery’s hiring typically involves 3–4 rounds, assessing cognitive, technical, and behavioral skills. The process can differ slightly for on-campus, off-campus, or experienced candidates.

Application Screening :

*
Candidates apply through Delhivery’s official careers page (careers.delhivery.com), job portals (e.g., Naukri, Indeed, LinkedIn), or campus placements.

* Resumes are screened for relevant skills, experience, and academic qualifications (e.g., 60%+ in 10th, 12th, and graduation for freshers, no pending backlogs).

* Required documents include ID proof, address proof, academic mark sheets, and optionally a passport or application receipt.


Online Assessment (for Technical/Managerial Roles):

* Conducted on platforms like HackerEarth, this round includes:

* Multiple-Choice Questions (MCQs): Cover computer science fundamentals (e.g., OS, DBMS, computer networks, OOPS, SQL queries) and aptitude (logical reasoning, English, mental ability).

* Coding Questions: 2–3 problems of easy to medium difficulty (e.g., data structures like arrays, trees, graphs, or algorithms like binary search, fractional knapsack).

* Duration: Typically 1–2 hours.

* For non-technical roles (e.g., operations), this may involve aptitude tests or role-specific questions (e.g., supply chain processes).


Technical Interviews (1–2 Rounds):

* Format: Virtual (e.g., Google Meet) or in-person, lasting 30–60 minutes.

* Focus Areas:

* Data Structures and Algorithms (DSA): Medium to hard-level questions (e.g., LeetCode-style problems on trees, maps, or graphs). Interviewers may expect specific solutions with matching time complexity.

* Project Discussion: Questions about resume projects, technologies used (e.g., React, JavaScript), and their implementation.

* Core Subjects: DBMS, OS, computer networks, SQL queries, low-level/high-level design for experienced candidates.

* Coding: Live problem-solving or machine coding (e.g., creating a password strength checker in React).

* For operations roles, questions may cover supply chain optimization, last-mile logistics, or dispute resolution.

* Interviewers assess problem-solving, communication, and technical depth.


HR Round:

*
Focuses on cultural fit, salary negotiation, and behavioral questions (e.g., “Why Delhivery?”, “How do you handle team disputes?”).

* May include situational questions or discussions about leadership principles.

* For delivery personnel, this may involve basic oral interviews and form-filling (e.g., PF, ESIC).


Document Verification:

* Verification of academic certificates, ID, and address proof.

* For delivery roles, additional steps like filling out company forms or ID card issuance may occur.


Specific Processes


Delivery Personnel:

*
Simplified process: Application, oral/written interview, form-filling, and document verification.

* Three-step hiring: Personal interview, assignment, final interview.

* Candidates apply via Delhivery’s careers page or local recruitment drives.


Training and Recruitment Program:

For entry-level managerial roles, candidates must clear an entrance exam and complete a 5-week training program for assured placement.
Some candidates report delays in communication post-exam or HR rounds.


Software Developer Roles:

*
Typically 2–3 rounds: Online coding/MCQ test, technical interview(s), and HR round.

* Coding questions focus on DSA (e.g., binary search, tree-based problems) and practical applications (e.g., SQL joins, aggregation).

* Campus interviews may include an initial online assessment with 2–3 coding questions and MCQs on C fundamentals, SQL, or DBMS.


Eligibility Criteria


Freshers:

*
B.E./B.Tech/M.Sc. in Computer Science or related fields.

* Minimum 60% throughout academics (10th, 12th, graduation).

* No pending backlogs.

* Strong communication, aptitude, and reasoning skills.


Experienced Candidates:

*
Relevant experience in logistics, supply chain, or software development.

* For technical roles, proficiency in DSA, system design, and specific technologies (e.g., React, SQL).


Delivery Roles:

* Flexible academic requirements but good calculation skills and shift availability.


Key Details


* Duration : The process takes 1–2 weeks for technical roles (as short as 2 days for some) and up to 95 days for senior roles like Product Manager.

* Salary :

* Freshers: ₹3–4.5 LPA (general roles), up to ₹6.5 LPA for digital skills.

* Varies by role, educational background, and college tier.

* Preparation Tips:

* Practice DSA and puzzles on platforms like InterviewBit or LeetCode.

* Be ready to discuss resume projects in detail.

* Brush up on core CS subjects (OS, DBMS, networks) and SQL.

* Improve communication through mock interviews.

* Candidate Experiences:

* Interviews are generally smooth, with supportive panels, but some report ghosting by HR or rigid expectations for DSA solutions.

* Operations roles may involve questions about e-commerce processes or last-mile logistics costs.

How to Apply

* Visit Delhivery’s careers page (delhivery.com) for open positions.

* Check job portals like Indeed, LinkedIn, or Instahyre for listings.

* For campus drives, follow college placement cells or FreshersNow for updates.

* Register for the Training and Recruitment Program via specific links.

Delhivery Interview Questions :

1 .
Why do you want to join Delhivery?
Sample Answer (Customizable):

"I want to join Delhivery because it’s one of the most innovative and fast-growing logistics companies in India. I admire how Delhivery uses technology and data-driven solutions to solve real-world supply chain problems. The company’s vision to redefine logistics in India and globally really aligns with my own interests in tech-enabled operations and problem-solving.

I’m excited by the opportunity to be part of a team that values efficiency, customer-centricity, and innovation. I believe Delhivery’s fast-paced, dynamic environment would be a great place to learn, contribute, and grow professionally."


You Can Personalize It Based On:
Area How to Personalize
Role Mention specific skills (e.g., "As a data analyst, I admire Delhivery’s use of AI for route optimization.")
Values Refer to their startup-to-unicorn journey, their culture of innovation, or focus on sustainability
Tech Talk about their platforms, use of automation, or how tech is used to streamline operations
Career Growth Emphasize opportunities to grow, learn, and be part of large-scale impact projects
2 .
What do you know about Delhivery and its services?

Delhivery is one of India’s leading logistics and supply chain companies, founded in 2011. It started as a hyperlocal delivery service but quickly evolved into a full-stack logistics provider.

The company offers a wide range of services including:

  • Parcel transportation (for e-commerce and businesses)

  • Warehousing & fulfillment

  • Freight services (including PTL/FTL)

  • Cross-border logistics

  • Supply chain software solutions

What sets Delhivery apart is its strong focus on technology and automation — they use AI, data analytics, and real-time tracking to optimize deliveries and reduce turnaround time. They have one of the largest pan-India delivery networks and are known for serving not just metro cities, but also remote areas across India.

They’ve also made key acquisitions and partnerships to expand capabilities, including Spoton Logistics, and went public with an IPO in 2022. Their goal is to become a fully integrated logistics player — flexible, tech-first, and scalable.

3 .
Describe a challenging situation you've faced and how you handled it.

Situation: During my final year project, we were working on a web app with a tight 2-week deadline. One week in, our main developer had a personal emergency and couldn't continue.

Task: As the team lead, I had to ensure the project stayed on track without compromising quality, despite being down a key team member.

Action: I reassigned tasks based on everyone’s strengths, took on additional coding myself, and kept in constant communication with the team to make sure everyone was aligned. I also worked late hours to fill the gaps, especially on the backend functionality.

Result: We completed the project just in time, delivered a functional prototype, and even received appreciation for the UI and presentation. More importantly, I learned how to stay calm under pressure, adapt quickly, and support a team through a crisis.

4 .
How do you handle pressure or tight deadlines?

I handle pressure and tight deadlines by staying organized, focused, and maintaining a calm mindset. When I know time is limited, I start by breaking the task into smaller, manageable parts and prioritize based on urgency and impact.

I also make sure to communicate clearly with my team or manager about progress, any blockers, and realistic expectations. If needed, I don’t hesitate to put in extra effort to meet the deadline — but I always ensure quality doesn’t suffer.

One thing I’ve learned is that pressure often comes from uncertainty — so by planning ahead, staying focused, and being adaptable, I can deliver even in high-pressure situations.

5 .
What is paging in memory management?

Paging is a memory management technique used by operating systems to manage and allocate memory efficiently. It allows a computer's physical memory to be divided into fixed-size blocks called pages and enables processes to use non-contiguous memory allocation. Paging facilitates virtual memory, allowing programs to run as if they have access to more memory than physically available.

Key Concepts of Paging
  1. Pages and Page Frames:
    • Physical memory is divided into fixed-size blocks called page frames.
    • A process's virtual address space is divided into fixed-size blocks called pages.
    • The size of a page is typically equal to the size of a page frame (e.g., 4 KB).
  2. Virtual Memory:
    • Each process has its own virtual address space, which is mapped to physical memory using paging.
    • Virtual addresses are translated to physical addresses by the Memory Management Unit (MMU) using a page table.
  3. Page Table:
    • A data structure maintained by the OS for each process to map virtual pages to physical page frames.
    • Each entry in the page table contains:
      • The physical address of the page frame.
      • Metadata like valid/invalid bits, protection bits, and dirty bits.
    • The page table is stored in memory, and a Translation Lookaside Buffer (TLB) is used to cache frequently accessed mappings for faster address translation.
  4. Address Translation:
    • A virtual address is divided into:
      • Page Number: Identifies the virtual page.
      • Offset: Specifies the location within the page.
    • The page number is used to look up the corresponding page frame in the page table, and the offset is added to get the final physical address.
    • Example:
      • Virtual address: 32 bits, page size: 4 KB (2^12 bytes).
      • Page number: Higher-order bits (e.g., 20 bits).
      • Offset: Lower-order bits (12 bits).
  5. Swapping:
    • If physical memory is full, less-used pages can be moved to secondary storage (e.g., a swap file on disk).
    • When needed, these pages are brought back into memory, a process called page fault handling.

Advantages of Paging
  • Non-contiguous Allocation: Processes can use non-contiguous physical memory, reducing fragmentation.
  • Virtual Memory: Enables programs to use more memory than physically available by swapping pages to disk.
  • Isolation: Each process has its own page table, ensuring memory protection and preventing unauthorized access.
  • Efficient Memory Utilization: Fixed-size pages simplify memory allocation and management.

Disadvantages of Paging
  • Overhead: Page tables consume memory, especially for large address spaces.
  • Page Faults: Accessing a page not in memory causes a page fault, requiring disk I/O, which is slow.
  • Internal Fragmentation: If a process doesn’t fully utilize a page, the unused portion wastes memory.
  • Translation Overhead: Address translation via page tables adds computational overhead, though mitigated by TLB.

Example in Context
  • In a system with a 4 KB page size, a process’s virtual address 8196 (in decimal) is translated:
    • Page size = 4 KB = 4096 bytes.
    • Page number = 8196 ÷ 4096 = 2 (integer division).
    • Offset = 8196 mod 4096 = 4.
    • The page table maps virtual page 2 to a physical page frame (e.g., frame 5). The physical address is (frame 5’s base address) + offset 4.

Relevance to Delhivery Interviews
  • Paging is a fundamental OS concept often asked in technical interviews for software developer roles at companies like Delhivery.
  • You might be asked to:
    • Explain how paging works or compare it with segmentation.
    • Discuss page table structures or handle page faults.
    • Solve problems related to address translation or memory allocation.
6 .
Explain the OSI model?
* OSI model which stands for open system interconnection model was proposed in 1983 to provide different functionalities for communication between networks.

* It was developed by the International Standards Organization (ISO) and it contains 7 layers, unlike the TCP/IP model which was proposed earlier and contains 5 layers.

* The seven layers of the OSI model are the Physical layer, Data Link layer, Network layer, Transport layer, Session layer, Presentation layer, and Application layer. All these layers provide different functionalities for communication in a network. All the layers of the OSI model are linked to each other.

The functionalities of different layers of the OSI model are :

* Physical Layer: Physical layer of the OSI model is the lowest layer among all and is responsible mainly for the physical connection between networks. The data is sent in the form of bits i.e. 0 and 1. Dealing with cables, repeaters, etc comes under the functionality of the physical layer.

* Data Link Layer: Data link layer is mainly responsible for converting the data into frames and transferring it from one node to another The data link layer is further divided into two layers namely MAC which stands for media access control and another one is LLC which stands for logic link control.

* Network Layer: The network layer provides the functionality of receiving the data in the form of frames from the data link layer and determining the route for sending the data to the destination using the logical addresses. It helps in selecting the optimal path from the source to the destination for the transfer of data.

* Transport Layer: Protocols such as TCP i.e transmission control protocols are present in this layer. The transport layer is responsible for delivering error-free data to the destination address. Acknowledgement of data that is sent through the network is essential and the transport layer takes care of that. If the acknowledgement is not received then the transport layer helps in retransmitting the data.

* Session Layer: The session layer is the 5th layer of the OSI model and functionalities such as providing security during the transmission of data in a network to keep our data safe, authentication, synchronization establishment, and termination of connections are provided by the session layer of OSI model.

* Presentation Layer: The presentation layer checks the data for syntax and semantics before sending it to the application layer. Other functionalities of the presentation layer include encrypting and describing the data and also reducing the size of data while transferring which is known as compression.

* Application Layer: Among the 7 layers of the OSI model, the application layer stands at the top. This layer is responsible for the interaction of the end-user with the application. This layer mainly helps in communicating with other devices. FTP, SMTP, and HTTP are the important protocols that are present in this layer.
7 .
Write a program for calculating the Stock Span
Problem Discussion:

You are given an array arr containing prices of the stock on different days. Your task is to calculate span i.e the number of days before the current day during which the price of the stock was equal to or less than the price at which the stock is trading on a given day.

The figure below shows the span of stocks on different days.

Algorithm :

* We will be using a stack for storing the index
* Create a span array and put 1 at the 0th index because the span for the first element will be 1.
* Create a stack and push the first index i.e. 0.
* Start traversing from the first index of the array and for each element:
* If the value of the current element is greater than the top element present in the stack then pop all the elements of the stack until the stack is empty or the value of the current element becomes less than the top element of the stack
* Now check whether the stack is empty or not.
* If the stack is empty that means that the current stock price is highest until now therefore store index+1 in the span array else store the difference between the current index and the top of the stack.

Implementation:
#include<stdbool.h>
#include<iostream>
using namespace std;
#include<string>

class node{
public:
 int data;
 class node* next;

 node()
 {
     data=0;
      next=NULL;
 }
}*top=NULL;

class Stack{

    public:

void push(int x){
       node *p=new node;
    if(top==NULL){

     p->data=x;
     p->next=NULL;
     top=p;}
     else{

     p->data=x;
     p->next=top;
     top=p;
     }
 }

 int pop(){
    int ch;
    ch=top->data;
    top=top->next;
    return ch;
 }

 bool isempty(){
 if(top==NULL){
 return true;}
 else{
    return false;
 }
 }

};

void stkspan(int arr[],int n){
    Stack st;
    int arr1[n];
    arr1[0]=1;
    st.push(0);
    for(int i=1;i<n;i++){

            while(st.isempty()==false && arr[i]>=arr[top->data])
            {
                st.pop();
            }
            if(st.isempty()==true)
            {
                arr1[i]=i+1;
            }
            else{
            arr1[i]=i-top->data;
            }
             st.push(i);

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

int main()
{
    int n;

cin>>n;
int *arr=new int[n];

for(int i=0;i<n;i++){
    cin>>arr[i];
}
stkspan(arr,n);
}​

Time and Space analysis :

* Time Complexity: O(N), where n is the number of elements in the array.
* Space Complexity: O(N), where n is the number of elements in the array.
8 .
Write a program to calculate the power of a number.
Algorithm:

* The approach is simple. We will use the divide and conquer method i.e we will divide a larger problem into subproblems recursively for calculation of the power of a number.

* In the base case return 1 since the power of any number to the power 0 is 1.

* We will store the recursive function in a temporary variable instead of calling the function 2 times to optimize the solution from O(N) to log(N).

Implementation:
#include<iostream>
using namespace std;
class Interviewbit
{
      
public:
int pow_function(int a, unsigned int b)
{  int x;
    if (b == 0){
        return 1;
    }
     x=pow_function(a, b / 2);
     if (b % 2 == 0){
        return x * x;}
    else{
        return a * x * x;
    }
}
};
 
int main()
{
    Interviewbit i;
    int a = 4;
    unsigned int b = 6;
 
    cout << i.pow_function(a, b);

}​

Time and Space analysis:

* Time Complexity: O(log n)
* Auxiliary Space: O(1)
9 .
State some of the uses of normalization?
* When we are dealing with a large amount of data the chances of redundancy increase therefore normalization helps in decreasing redundancy.

* In order to decrease complexity, normalization looks at the new data types added to the table.

* A big database table can be broken up into smaller tables and linked with relationships.

* Anomalies are less likely to appear in a database with the help of normalization.
10 .
Write a program to create and insert a new node in a binary tree in a level order manner

Here's a simple program in Python to create a binary tree and insert a new node in level order (i.e., fill the tree from left to right, top to bottom):


Binary Tree Level-Order Insertion (Python)
from collections import deque

# Define a Node
class Node:
    def __init__(self, key):
        self.data = key
        self.left = None
        self.right = None

# Function to insert a new node in level order
def insert_level_order(root, key):
    if not root:
        return Node(key)

    queue = deque()
    queue.append(root)

    while queue:
        temp = queue.popleft()

        if not temp.left:
            temp.left = Node(key)
            return root
        else:
            queue.append(temp.left)

        if not temp.right:
            temp.right = Node(key)
            return root
        else:
            queue.append(temp.right)

# Helper function to do level order traversal (for visualization)
def level_order_traversal(root):
    if not root:
        return []

    result = []
    queue = deque()
    queue.append(root)

    while queue:
        node = queue.popleft()
        result.append(node.data)

        if node.left:
            queue.append(node.left)
        if node.right:
            queue.append(node.right)

    return result

# Example Usage
if __name__ == "__main__":
    # Create a simple tree
    root = Node(10)
    root.left = Node(11)
    root.left.left = Node(7)
    root.right = Node(9)
    root.right.left = Node(15)
    root.right.right = Node(8)

    print("Level order before insertion:", level_order_traversal(root))

    key_to_insert = 12
    insert_level_order(root, key_to_insert)

    print("Level order after insertion:", level_order_traversal(root))

How It Works:
  • It uses a queue to perform level order traversal.

  • It checks each node’s left and right child.

  • The first place it finds a missing child (None), it inserts the new node.

11 .
Write code to check if a number is a palindrome.

Sure! Here's a simple program in Python to check if a number is a palindrome — meaning it reads the same backward as forward.


Python Code: Check Palindrome Number
def is_palindrome(num):
    # Convert number to string
    str_num = str(num)
    
    # Compare with its reverse
    return str_num == str_num[::-1]

# Example usage
number = 121
if is_palindrome(number):
    print(f"{number} is a palindrome.")
else:
    print(f"{number} is not a palindrome.")

Explanation:
  • We convert the number to a string.

  • Then compare it with its reversed version using slicing ([::-1]).


Optional: Without converting to string

If you want a pure number-based solution, here’s how:

def is_palindrome_number(num):
    original = num
    reversed_num = 0

    while num > 0:
        digit = num % 10
        reversed_num = reversed_num * 10 + digit
        num //= 10

    return original == reversed_num

# Example usage
number = 12321
if is_palindrome_number(number):
    print(f"{number} is a palindrome.")
else:
    print(f"{number} is not a palindrome.")
12 .
Find the factorial of a number using recursion.

Sure! Here's a simple recursive function in Python to calculate the factorial of a number.


Python Code: Factorial Using Recursion:
def factorial(n):
    # Base case
    if n == 0 or n == 1:
        return 1
    # Recursive case
    return n * factorial(n - 1)

# Example usage
num = 5
print(f"Factorial of {num} is {factorial(num)}")

How It Works:
  • factorial(5)5 * factorial(4)

  • factorial(4)4 * factorial(3)

  • ... until it hits the base case: factorial(1)1

So:

factorial(5) = 5 * 4 * 3 * 2 * 1 = 120
13 .
Find the largest element in an array.

Sure! Here's a simple program in Python to find the largest element in an array:


Python Code: Find Largest Element in an Array
def find_largest(arr):
    if not arr:
        return None  # Handle empty array

    largest = arr[0]

    for num in arr:
        if num > largest:
            largest = num

    return largest

# Example usage
arr = [10, 45, 3, 99, 23, 67]
print(f"The largest element is: {find_largest(arr)}")

Explanation:
  • Start by assuming the first element is the largest.

  • Loop through the array and update if a bigger number is found.


Output for the example:
The largest element is: 99
14 .
Write a program to reverse a string with the help of stack
Algorithm:

* Create a string p of size n.
* Create a stack of size n to store all the char of the string
* Traverse the string using a loop from the left and push each and every character in the stack
* When you come out of the loop, create a loop again to pop the elements from the stack and store them in a string.
* Since stack follows LIFO i.e. last in first out, the popped string will be reversed.
* Return the reversed string and print it.

Implementation:
#include <bits/stdc++.h>
using namespace std;
 
class Stack{  
    public:
        int top;  
       int size;  
        char* array;  
};  
 
Stack* Stack_create(unsigned size){
    
    Stack* new_stk = new Stack();
    new_stk->size= size;  
    new_stk->top = -1;  
    new_stk->array = new char[(new_stk->size * sizeof(char))];  
    return new_stk;  
}  
 
int stackfull(Stack* stk){
    return stk->top == stk->size - 1;
}  
 
int stackempty(Stack* stk){
    return stk->top == -1;
}  
 
void push(Stack* stack, char item){  
    if (stackfull(stack))  
        return;  
    stack->array[++stack->top] = item;  
}  
 
char pop(Stack* stk){
    if (stackempty(stk))  
        return -1;  
    return stk->array[stk->top--];  
}  
 
void string_reverse(char p[]){  
    int n = strlen(p);  
    Stack* stk = Stack_create(n);  
 
    int i;  
    for(i = 0; i < n; i++){  
        push(stk, p[i]);
    }    
 
    for(i = 0; i < n; i++){  
        p[i] = pop(stk);
    }    
}  
 
int main(){  
    char p[] = "Welcome_To_InterviewBit";  
 
    string_reverse(p);  
    cout<<p<<endl;  
 
}​

Time and space analysis:

* Time Complexity: O(N)
* Auxiliary Space: O(N)
15 .
In what condition does the worst case of QuickSort occur?
* The worst case of the quick sort occurs when the array is sorted, resulting in time complexity of O(N2).

* We use the partitioning method in quick sort in which we select a pivot and find the correct position for that pivot element. The elements smaller than the pivot element are on one side and the greater elements are on the other side.

* If the array is sorted then partitioning happens at the end of the array resulting in time complexity of O(N2).
16 .
What is the basic difference between function overloading and function overriding?
Function overloading means 2 functions that are declared with the same name but have any one of the following parameters different among them:

* The number of arguments passed to the function can be different.
* The type of arguments passed can be different.
* The ordering of arguments in the function can be different.
* Function overriding is similar to overloading but in overriding both the functions are in different class i.e. base class and derived class whereas in overloading both functions are in the same class. Overriding is applied in the situations where a function is defined in the base class but more functionalities are defined in the derived class.
17 .
Rotate a matrix by 90 degrees in a clockwise manner.
Problem Discussion:

Suppose you are given a matrix:
mat[n][n] = { {1, 2, 3}, { 7,8,9  }, {  10, 11, 12 }, };​

Your task is to rotate this matrix by 90 degrees in a clockwise manner.

So the output will look like this:

10 7 1
11 8 2
12 9 3 ​

Algorithm :

To rotate the matrix by 90 degrees you just have to follow 2 steps:

* Take transpose of the matrix
* Reverse all the rows of the matrix

1  2  3                                                        1  7  10                                                            10  7   1

7  8  9             ——Transpose——>      2  8   11         —-Reverse  rows—->          11  8  2  

10  11  12                                                 3   9  12                                                           12  9  3


Implementation:

#include <iostream>
using namespace std;
const int n = 3;
void print(int given_matrix[n][n])
{
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++)
            cout << given_matrix[i][j] << " ";
        cout << endl;
    }
}
void rotate_a_matrix_by_90_degrees(int given_matrix[n][n])
{

    for (int i = 0; i < n; i++)
        for (int j = i + 1; j < n; j++)
            swap(given_matrix[i][j], given_matrix[j][i]);
 
    for (int i = 0; i < n; i++) {
        int left = 0, right = n - 1;
        while (left < right) {
            swap(given_matrix[i][left], given_matrix[i][right]);
            left++;
            right--;
        }
    }
}
int main()
{
    int given_matrix[n][n]
        = { {1, 2, 3},
                      { 7,8,9  },
                      {  10, 11, 12 },
                      };
    rotate_a_matrix_by_90_degrees(given_matrix);
    print(given_matrix);
}​


Time and space Analysis:

* Time Complexity – O(N2)
* Auxiliary Space – O(1)
18 .
Find 2 missing numbers
Problem Discussion:

* This is a follow up question of finding missing elements. If you successfully tell the approach for finding missing elements to the interviewer then you will surely get this follow up question. In the previous question, you were required to find a single missing element but in this question, you have to find 2 missing elements in the range 0 to n.

Algorithm:

* This question can be solved using xor operations efficiently.
* First of all take the xor of all the elements present in the array with natural numbers from 1 to n. For eg: If the given array is [1,2,4,6] then xor these with natural numbers from 1 to 6. This will give us 3^5. * But the problem is we don’t know which are the exact numbers that are missing, we just know the xor of those numbers.
* So to solve this problem we will consider the rightmost set bit in xor of 3 and 5. The rightmost bit can be calculated using the formula XOR & ~(XOR-1).
* In xor operation a set bit is formed by combination of 0 and 1. Therefore if we perform xor operation of all the elements in the array which have their rightmost set bit as 1 with all the natural numbers in the range then we will get the first missing number. Similarly, if we perform xor operation of all the elements in the array which do not  have their rightmost set bit as 1 with all the natural numbers in the range then we will get another missing number.

Implementation:
#include<bits/stdc++.h>
 
void function_for_missing(int nums[], int n)
{
 
    int XOR = nums[0];
    for (int i = 1; i < n-2; i++)
        XOR ^= nums[i];
    for (int i = 1; i <= n; i++)
        XOR ^= i;
 
    int set_bit_no = XOR & ~(XOR-1);

    int a = 0, b = 0;
    for (int i = 0; i < n-2; i++)
    {
        if (nums[i] & set_bit_no)
            a = a ^ nums[i];
        else
            b = b ^ nums[i];
    }
    for (int i = 1; i <= n; i++)
    {
        if (i & set_bit_no)
            a = a ^ i;
        else
            b = b ^ i;
    }
 
    printf("The numbers which are not present are\n %d %d", a, b);
}
 
int main()
{
    int nums[] = {1, 3, 5, 6};
 
    int n = 2 + sizeof(nums)/sizeof(nums[0]);
 
    function_for_missing(nums, n);
 
    return 0;
}​

Time and Space analysis:

* Time Complexity : O(n)

* Auxiliary Space : O(1)
19 .
Compare the different version numbers
Problem Discussion:

You are given version numbers and these are of the form w.x.y.z where x,y, z and w are strings which are separated by a dot. Your task is to compare two given strings/version numbers and return the version number which is smaller. Suppose you are given two versions 2.0 and 2.1 then 2.0 will be considered smaller.

For eg:

s1=7.0.1.23

s2=7.0.1.17

The output will be 7.0.1.17 because s2 is smaller

Algorithm:

* The given string or versions contain dots therefore we have to trace them part by part.
* Traverse the versions and compare the strings between dots.
* For comparing the string first compare them into integer
* Maintain two variables version1 and version2 for calculating the value between dots.
* If both the numbers between dots are equal make version1 and version2 zero and traverse again else return the version which is smaller.

Implementation:
#include <bits/stdc++.h>
using namespace std;
 
int check(string s1, string s2)
{
    int version1 = 0, version2 = 0;

    for (int i = 0, j = 0; (i < s1.length()
                            || j < s2.length());) {
   
        while (i < s1.length() && s1[i] != '.') {
            version1 = version1 * 10 + (s1[i] - '0');
            i++;
        }
 
        while (j < s2.length() && s2[j] != '.') {
            version2 = version2 * 10 + (s2[j] - '0');
            j++;
        }
        if (version1> version2)
            return 1;
        if (version2 > version1)
            return -1;

        version1 = version2= 0;
        i++;
        j++;
    }
    return 0;
}
 
int main()
{
    string s1 = "0.5.3";
    string s2 = "0.5.7";
 
    if (check(s1, s2) < 0)
        cout << s1 << " is smaller\n";
    else if (check(s1, s2) > 0)
        cout << s2 << " is smaller\n";
    else
        cout << "Both version are equal\n";
   
}​

Time and space analysis:

* Time Complexity: O(n), where n is the length of the string.
* Auxiliary space: O(1)
20 .
SQL Query: Fetch the second highest salary from a table.

To fetch the second highest salary from a table in SQL, here's a clean and commonly used query:


SQL Query (Using DISTINCT and LIMIT / OFFSET):
SELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 1;

Explanation:
  • ORDER BY salary DESC → Sorts salaries in descending order.

  • LIMIT 1 OFFSET 1 → Skips the highest salary (OFFSET 1) and returns the next one.


Table Assumption:

Assuming your table is named employees and has a column called salary.


Alternate Version (Using MAX with Subquery):
SELECT MAX(salary) AS second_highest_salary
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);

Notes:
  • The second query works even if there are duplicate salaries.

  • Use DISTINCT if the table contains duplicate salary entries and you want to ignore them.