Technical Interview Questions commonly asked during Campus Placement Drives

Technical Interview Questions commonly asked during Campus Placement Drives

Preparing for Success: A Comprehensive Guide to Common Technical Interview Questions in Campus Placement Drives

Data Structure and Algorithms [DSA]

Define the data structure.
A data structure is a mechanical or logical way that data is organized within a program. The organization of data is what determines how a program performs. There are many types of data structures, each with its own uses. When designing code, we need to pay particular attention to the way data is structured. If data isn't stored efficiently or correctly structured, then the overall performance of the code will be reduced.

What is Stack?
Stack is an ordered list in which, insertion and deletion can be performed only at one end which is called the top. It is a recursive data structure having a pointer to its top element. The stack is sometimes called a Last-In-First-Out (LIFO) list i.e. the element which is inserted first in the stack will be deleted last from the stack.

Define Push and Pop in Stack.
PUSH and POP operations specify how data is stored and retrieved in a stack.

  • PUSH: PUSH specifies that data is being "inserted" into the stack.

  • POP: POP specifies data retrieval. It means that data is being deleted from the stack.

Define Queue.
A queue is a linear data structure that allows users to store items in a list in a systematic manner. The items are added to the queue at the rear end until they are full, at which point they are removed from the queue from the front. A good example of a queue is any queue of customers for a resource where the first consumer is served first.

Define Array.
Arrays are defined as the collection of similar types of data items stored at contiguous memory locations. It is the simplest data structure in which each data element can be randomly accessed by using its index number.

Define LinkedList.
A linked list can be thought of as a series of linked nodes (or items) that are connected by links (or paths). Each link represents an entry into the linked list, and each entry points to the next node in the sequence. The order in which nodes are added to the list is determined by the order in which they are created.

Here's a chart depicting various LinkedList operations in DSA, along with their definitions and the time complexities for the best, worst, and average cases:

OperationDefinitionBest CaseWorst CaseAverage Case
Insertion (Front)Add an element at the beginning of the LinkedList.O(1)O(1)O(1)
Insertion (End)Add an element at the end of the LinkedList.O(1)O(1)O(1)
Insertion (Middle)Add an element at a specific position in the LinkedList.O(1) to O(N)O(N)O(N/2)
Deletion (Front)Remove the first element from the LinkedList.O(1)O(1)O(1)
Deletion (End)Remove the last element from the LinkedList.O(N)O(N)O(N)
Deletion (Middle)Remove an element from a specific position in the LinkedList.O(1) to O(N)O(N)O(N/2)
SearchFind an element in the LinkedList.O(1)O(N)O(N)
Access (By Index)Access an element by its index in the LinkedList.O(1)O(N)O(N)
TraverseVisit all elements in the LinkedList.O(N)O(N)O(N)

Define Binary Tree.
A Binary Tree is a hierarchical data structure in computer science consisting of nodes, where each node can have at most two children, commonly referred to as the left child and the right child. The topmost node is called the root, and nodes with no children are called leaf nodes. Binary trees are widely used for efficient searching, sorting, and organizing data.

  • Maximum number of nodes in a binary tree of height K, 2k+1-1 where k >= 1.

Define AVL Tree.
AVL trees are height-balancing binary search trees named after their inventors Adelson, Velski, and Landis. The AVL tree compares the heights of the left and right subtrees and ensures that the difference is less than one. This distinction is known as the Balance Factor.
Formula to find Balance Factor, BalanceFactor = height(left-subtree) − height(right-subtree)

Define Graph.
A graph G can be defined as an ordered set G(V, E) where V(G) represents the set of vertices and E(G) represents the set of edges that are used to connect these vertices. A graph can be seen as a cyclic tree, where the vertices (Nodes) maintain any complex relationship among them instead of having parent-child relations.

  • Path: A Path is the sequence of adjacent vertices connected by the edges with no restrictions.

  • Cycle: A Cycle can be defined as the closed path where the initial vertex is identical to the end vertex. Any vertex in the path can not be visited twice

  • Circuit: A Circuit can be defined as a closed path where the initial vertex is identical to the end vertex. Any vertex may be repeated.

What is the difference between Null and Void?

  • Null is a value, whereas Void is a data type identifier.

  • A null variable simply indicates an empty value, whereas a void is used to identify pointers as having no initial size.

What is Binary Search Tree (BST)?
A binary search tree is a data structure that stores items in sorted order. In a binary search tree, each node stores a key and a value. The key is used to access the item and the value is used to determine whether the item is present or not. The key can be any type of value such as an integer, floating point number, character string, or even a combination of these types. The value can be any type of items such as an integer, floating point number, character string, or even a combination of these types. When a node is added to the tree, its key is used to access the item stored at that node. When a node is removed from the tree, its key is used to access the item stored at that node.

Difference between BFS and DFS.

Breadth First Search (BFS)Depth First Search (DFS)
It stands for “Breadth-First Search”It stands for “Depth First Search”
BFS (Breadth First Search) finds the shortest path using the Queue data structure.DFS (Depth First Search) finds the shortest path using the Stack data structure.
We walk through all nodes on the same level before passing to the next level in BFS.DFS begins at the root node and proceeds as far as possible through the nodes until we reach the node with no unvisited nearby nodes.
When compared to DFS, BFS is slower.When compared to BFS, DFS is faster.
BFS performs better when the target is close to the source.DFS performs better when the target is far from the source.

Searching Techniques overview in a single chart.

TechniqueDefinitionBest Case ComplexityWorst Case ComplexityAverage Case Complexity
Linear SearchSequentially searches for an element in a list/array.O(1)O(n)O(n)
Binary SearchSearches for an element in a sorted list/array.O(1)O(log n)O(log n)
Jump SearchJumps ahead by a fixed step in a sorted list/array.O(1)O(√n)O(√n)
Interpolation SearchSearches in uniformly distributed sorted list/array.O(1)O(log log n)O(log log n)
Exponential SearchUtilizes exponential growth to search in a sorted list/array.O(1)O(log n)O(log n)
Hash Table LookupUses a hash function to search for elements in a hash table.O(1)O(n)O(1)

Sorting Techniques overview in a single chart.

Sorting TechniqueDefinitionBest CaseWorst CaseAverage Case
Bubble SortCompares adjacent elements and swaps them if they are in the wrong order. Repeats until the array is sorted.O(n)O(n^2)O(n^2)
Selection SortDivides the input array into two parts: the sorted part and the unsorted part. Repeatedly selects the smallest element from the unsorted part and moves it to the sorted part.O(n^2)O(n^2)O(n^2)
Insertion SortBuilds the final sorted array one item at a time. Iterates through the input array, and for each element, finds its correct position in the sorted part.O(n)O(n^2)O(n^2)
Merge SortDivides the input array into two halves, sorts each half recursively, and then merges them back together.O(n log n)O(n log n)O(n log n)
Quick SortChooses a pivot element, partitions the array into two sub-arrays (elements smaller than pivot and elements greater than pivot), and recursively sorts the sub-arrays.O(n log n)O(n^2)O(n log n)
Heap SortBuilds a max-heap from the input array and repeatedly extracts the maximum element from the heap to form the sorted array.O(n log n)O(n log n)O(n log n)
Counting SortAssumes that the input consists of integers within a specific range. Counts the occurrences of each element and uses this information to place elements in the correct order.O(n + k)O(n + k)O(n + k)
Radix SortSorts the elements digit by digit, from the least significant digit to the most significant digit.O(nk)O(nk)O(nk)

Database Management Systems [DBMS]

What is Database Management Systems?
DBMS stands for "Database Management System." It is software that facilitates the creation, organization, and manipulation of databases, allowing users to store, retrieve, and manage data efficiently and securely.

Differentiate between DBMS and RDBMS.
DBMS (Database Management System):

  • Manages and organizes data in a database.

  • Supports basic operations like storing, retrieving, updating, and deleting data.

  • May not enforce strict relationships between tables.

  • Example: File-based systems.

RDBMS (Relational Database Management System):

  • A type of DBMS that organizes data into tables with predefined relationships between them.

  • Enforces the ACID properties for transaction management.

  • Provides a structured way to define and manipulate data using SQL (Structured Query Language).

  • Example: MySQL, Oracle, PostgreSQL.

Explain the three levels of data abstraction in DBMS.
The three levels of data abstraction in DBMS are:

  1. Physical Level: Deals with how data is stored in the database at the lowest level, focusing on data storage structures and access methods.

  2. Logical Level: Concerned with describing data in terms of the database schema, defining the relationships and constraints.

  3. View Level: Provides a customized, user-specific view of the data, showing only the relevant information, hiding the underlying complexity of the database.

What is normalization, and why is it important in database design?
Normalization is the process of organizing data in a database efficiently by reducing redundancy and dependency. It is important in database design to eliminate data anomalies, improve data integrity, and optimize storage space.

Define ACID properties.
ACID properties of a transaction in a DBMS are:

  1. Atomicity: A transaction is treated as a single, indivisible unit of work. It either fully succeeds (commits) or fully fails (rolls back) if an error occurs.

  2. Consistency: A transaction brings the database from one valid state to another. It ensures that all constraints and rules are followed during the transaction.

  3. Isolation: Each transaction is executed in isolation from others, ensuring that the intermediate states of one transaction are not visible to others until it is committed.

  4. Durability: Once a transaction is committed, its changes are permanent and survive system failures. The changes become a permanent part of the database.

What are the primary key and foreign key? How are they related?
A primary key is a unique identifier for a record in a database table, ensuring each row has a distinct value. It uniquely identifies a single record.

A foreign key is a field in a table that points to the primary key of another table, creating a relationship between the two tables.

In summary, a primary key uniquely identifies records within its table, while a foreign key establishes a link to the primary key of another table, enabling the establishment of relationships between tables in a database.

What are the different types of joins in SQL?

  • INNER JOIN: Returns only the matching rows from both tables.

  • LEFT JOIN (or LEFT OUTER JOIN): Returns all rows from the left table and matching rows from the right table.

  • RIGHT JOIN (or RIGHT OUTER JOIN): Returns all rows from the right table and matching rows from the left table.

  • FULL JOIN (or FULL OUTER JOIN): Returns all rows when there is a match in either the left or right table.

  • SELF JOIN: Joins a table with itself based on a related column.

  • CROSS JOIN: Produces a Cartesian product of rows from both tables (all possible combinations).

  • NATURAL JOIN: Joins tables based on columns with the same name, eliminating duplicate columns. (Less commonly used due to ambiguity risks)

Explain the differences between DELETE, TRUNCATE, and DROP commands in SQL.

  • DELETE: Removes rows one by one from a table based on the specified condition. It is a DML (Data Manipulation Language) command and can be rolled back.

  • TRUNCATE: Removes all rows from a table in one shot. It is a DDL (Data Definition Language) command and cannot be rolled back. It also resets identity/auto-increment values.

  • DROP: Completely removes a table from the database, along with its data and structure. It is a DDL (Data Definition Language) command and cannot be rolled back.

What is the role of the COMMIT and ROLLBACK statements in a transaction?

  • COMMIT: The COMMIT statement is used to permanently save the changes made in a transaction to the database.

  • ROLLBACK: The ROLLBACK statement is used to undo the changes made in a transaction and restore the database to its state before the transaction started.

Aggregate Functions in SQL.
Aggregate functions in SQL are functions used to perform calculations on sets of values and return a single result. Common aggregate functions include SUM(), COUNT(), AVG(), MAX(), and MIN().

Write a SQL query to fetch data from multiple tables using JOIN.

SELECT employees.employee_id, employees.employee_name, employees.salary, 
departments.department_name FROM employees 
JOIN departments 
ON employees.department_id = departments.department_id;

Write a query to find the highest/lowest value in a specific column of a table.

-- -- Finding out the Highest Value of a particular column
SELECT MAX(column_name) AS highest_value
FROM table_name;

-- Finding out the Lowest Value of a particular column
SELECT MIN(column_name) AS lowest_value
FROM table_name;

Write the SQL query to get the third maximum salary of an employee from a table named employees.

SELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
LIMIT 2, 1;

Display the first and last record from the Employee table.

SELECT * FROM Employee ORDER BY employee_id LIMIT 1
UNION ALL
SELECT * FROM Employee ORDER BY employee_id DESC LIMIT 1;

◆ Display the total salary of each employee after adding 18% increment in the salary.

SELECT employee_id, employee_name, salary, (salary * 1.18) AS total_salary
FROM Employee;

Write an SQL query for creating a new column named password for each of the employees. Password format, the first three characters of their name + the last three digits of their phone number.

ALTER TABLE Employee
ADD password VARCHAR(100);

UPDATE Employee
SET password = CONCAT(SUBSTRING(employee_name, 1, 3), RIGHT(phone_number, 3));

Write a query to return the number of employees whose DOB is between 01/01/1990 to 01/01/2001 and are grouped according to gender.

SELECT gender, COUNT(*) AS number_of_employees
FROM Employee
WHERE date_of_birth BETWEEN '1990-01-01' AND '2001-01-01'
GROUP BY gender;

Object Oriented Programming

What do you understand by OOP?
OOP stands for object-oriented programming. It is a programming paradigm that revolves around the object rather than function and procedure. In other words, it is an approach for developing applications that emphasize on objects. An object is a real word entity that contains data and code. It allows binding data and code together.

What are the four main features of OOPs?
The four main features of Object-Oriented Programming (OOP) are:

  1. Encapsulation: Bundling data (attributes) and methods (functions) together as objects to hide the internal implementation details and expose only relevant functionalities.

  2. Abstraction: Simplifying complex real-world entities into classes and objects, providing a clear interface for interaction while hiding unnecessary details.

  3. Inheritance: Creating new classes (derived or child classes) based on existing classes (base or parent classes), inheriting their attributes and methods to promote code reusability.

  4. Polymorphism: The ability of objects to take on multiple forms, allowing different classes to be treated as instances of a common superclass and enabling method overriding and method overloading.

Differentiate between a class and an object in OOP.

  • Class: A class in Object-Oriented Programming is a blueprint or template that defines the properties (attributes) and behaviors (methods) that objects of that class will have.

  • Object: An object is an instance of a class, created from the class blueprint. It represents a specific entity and encapsulates its own set of data and behavior defined by the class.

Define Method Overloading and Method Overriding.

  • Method Overloading: Method overloading is a feature in OOP where multiple methods in the same class have the same name but differ in the number or type of parameters they accept. It allows a single method name to perform different tasks based on the input provided.

  • Method Overriding: Method overriding is a concept in OOP where a subclass provides a specific implementation for a method that is already defined in its superclass. The subclass method with the same name and signature as the superclass method replaces the superclass method's behavior in the subclass.

What are the different types of Polymorphism? How we can achieve them?

  1. Compile-time Polymorphism (Static Polymorphism):

    • Achieved through method overloading.

    • Multiple methods with the same name but different parameters are defined in a class.

    • The appropriate method is determined at compile-time based on the number or types of arguments passed.

  2. Runtime Polymorphism (Dynamic Polymorphism):

    • Achieved through method overriding.

    • A subclass provides a specific implementation for a method that is already defined in its superclass.

    • The appropriate method is determined at runtime based on the actual object type rather than the reference type.

Both types of polymorphism enable a single method name to behave differently based on the context, leading to more flexible and reusable code in Object-Oriented Programming.

What is Abstract Class and Interface?

Abstract Class:

  • An abstract class is a class that cannot be instantiated and serves as a blueprint for other classes.

  • It may contain abstract methods (without implementation) and concrete methods (with implementation).

  • Subclasses (derived classes) must provide implementations for all abstract methods defined in the abstract class.

Interface:

  • An interface is a collection of abstract methods and constants.

  • It defines a contract for classes that implement it, specifying the methods they must provide.

  • Classes can implement multiple interfaces, enabling multiple inheritances in Java and other languages that support interfaces.

What is Multithreading in Java?
Multithreading in Java is the ability of a program to execute multiple threads (small units of a process) concurrently, allowing it to perform multiple tasks simultaneously and make better use of available resources. Each thread runs independently, and the Java Virtual Machine (JVM) manages their execution, switching between them rapidly to create the illusion of parallelism. Multithreading enhances the performance of Java applications, especially in scenarios where tasks can be executed concurrently, such as handling user interfaces, background processing, or network communication.

What is Thread in Java?
A thread in Java is the smallest unit of execution within a process. It allows a program to perform multiple tasks simultaneously, making it possible to achieve concurrent execution and better utilize CPU resources. Threads share the same memory space and resources of their parent process, but each thread has its own execution path, allowing independent execution of code segments concurrently.

What is Constructor in Java?
In Java, a constructor is a special method within a class that is automatically called when an object of that class is created. It is used to initialize the object's state and perform any setup operations required for the object to function correctly. Constructors have the same name as the class and do not have a return type, not even void. They can be used to set default values, allocate memory, or perform any other necessary tasks before the object is ready for use.

What is Method in Java?
In Java, a method is a block of code that performs a specific task or operation. It is a fundamental building block of object-oriented programming. Methods are defined within classes and can be called to execute the code they contain. They help in organizing and reusing code, making programs more efficient and maintainable.

Example of a method that adds two numbers and returns the result:

public int addNumbers(int a, int b) {
    int sum = a + b;
    return sum;
}

What is Deadlock in Java?
Deadlock in Java is a situation where two or more threads are unable to proceed with their execution because each of them is waiting for a resource (such as a lock or a shared variable) that is held by another thread in the same set of threads. As a result, all the threads become blocked, and the application comes to a standstill, unable to make any further progress. Deadlocks are undesirable and need to be carefully handled to ensure the smooth execution of multithreaded Java programs.

◆ Define Collection Frameworks in Java.
Collection Frameworks in Java provide a set of pre-built data structures and algorithms to efficiently store, manage, and manipulate collections of objects. They offer interfaces and classes like List, Set, Map, etc., which are widely used for organizing, searching, and processing data. Collection Frameworks simplify coding tasks, promote code reuse, and enhance the performance and scalability of Java applications.

What is an Exception in Java?
An exception in Java is an event that occurs during the execution of a program, disrupting the normal flow of code due to an error or unexpected situation. When an exception occurs, Java creates an object representing the specific error and throws it to indicate that something went wrong. Exception handling mechanisms, such as try-catch blocks, allow programmers to handle these exceptions gracefully, ensuring the program doesn't crash and providing a way to recover from errors.

What is Exception Handling in Java?
Exception handling in Java is a mechanism used to deal with errors and unexpected situations that occur during the execution of a program. It allows developers to handle exceptions gracefully, preventing the program from crashing and providing a way to recover from errors.

What do you mean by public static void main (String[] args) in Java?
Let's break down the components of this method signature:

  1. public: It is an access modifier that indicates the method can be accessed from anywhere in the program. It allows the JVM to call the main method from outside the class.

  2. static: It is a keyword that denotes that the method belongs to the class and not to an instance of the class. The main method is called by the JVM without creating an instance of the class, hence it must be static.

  3. void: It is the return type of the method, indicating that the main method does not return any value.

  4. main: It is the name of the method and serves as the identifier for the JVM to recognize it as the entry point.

  5. String[] args: It is the parameter of the main method. It is an array of strings that allows you to pass command-line arguments to the Java program.

Define JVM, JDK, JRE, Byte Code.

JVM (Java Virtual Machine):

  • JVM is an integral part of the Java Runtime Environment (JRE).

  • It is a virtual machine that enables Java programs to run on any platform, providing a platform-independent execution environment.

  • JVM interprets Java bytecode and converts it into machine-specific code during runtime.

JDK (Java Development Kit):

  • JDK is a software development kit provided by Oracle (previously Sun Microsystems) for developing Java applications.

  • It includes tools such as the Java compiler (javac), debugger (jdb), and other utilities needed for Java development.

  • JDK also contains JRE, allowing developers to run Java programs during development.

JRE (Java Runtime Environment):

  • JRE is the runtime environment required to run Java applications and applets.

  • It includes the JVM, Java libraries, and other supporting files needed to execute Java programs.

  • JRE does not contain development tools; it is used for running Java applications only.

Bytecode:

  • Bytecode is an intermediate representation of Java source code after it is compiled by the Java compiler.

  • It is a set of instructions in the form of bytecode, which is platform-independent and can be executed by the JVM.

  • Java source code (.java files) is compiled into bytecode (.class files), and the JVM interprets and executes this bytecode on any platform.

Advantages of using Java.

  1. Platform Independence: Java programs can run on any platform with a Java Virtual Machine (JVM), ensuring cross-platform compatibility.

  2. Object-Oriented: Java's object-oriented approach promotes modularity, reusability, and easier maintenance of code.

  3. Robust and Secure: Java's strong type-checking and exception handling make it robust and less prone to errors. Its built-in security features protect against malicious code.

  4. Garbage Collection: Automatic memory management through garbage collection reduces the risk of memory leaks and manual memory management errors.

  5. Rich Standard Library: Java provides a vast standard library with a wide range of APIs, making development faster and more efficient.

  6. Multithreading: Built-in support for multithreading allows concurrent execution, improving performance on multi-core processors.


Software Engineering

What is SDLC, and what are its different phases?
SDLC stands for Software Development Life Cycle. It is a systematic approach used to design, develop, and maintain software. The different phases of SDLC are:

  1. Requirements Gathering: Collecting and understanding the needs of the software to be developed.

  2. Analysis and Planning: Analyzing requirements, feasibility, and creating a development plan.

  3. Design: Creating a detailed blueprint of the software's architecture and functionality.

  4. Implementation: Writing code based on the design and creating the actual software.

  5. Testing: Verifying the software for errors, bugs, and functionality issues.

  6. Deployment: Releasing the software for users.

  7. Maintenance: Regularly updating and enhancing the software to meet changing requirements and fixing issues.

These phases ensure a structured approach to software development, resulting in a high-quality product.

Explain the Waterfall model.

The Waterfall model is a linear and sequential software development approach. It follows a structured and rigid process where each phase must be completed before moving on to the next one. The phases of the Waterfall model include:

  1. Requirements: Gather and document all the project requirements.

  2. Design: Create a detailed design plan based on the gathered requirements.

  3. Implementation: Develop the software based on the design specifications.

  4. Testing: Verify and validate the software to identify defects and errors.

  5. Deployment: Deploy the tested software to the production environment.

  6. Maintenance: Provide ongoing support and updates to the software.

In the Waterfall model, there is minimal room for changes or iterations once a phase is completed, making it suitable for well-defined projects with stable requirements. However, it may not be the best fit for complex or uncertain projects where requirements are likely to change during development.

What is Agile Methodology?
Agile methodology is an iterative and incremental approach to software development. It prioritizes flexibility, customer collaboration, and delivering working software in short iterations called "sprints." Teams work in close collaboration with stakeholders, adapt to changing requirements, and focus on continuous improvement throughout the development process. This approach promotes quick response to feedback, embraces change, and aims to deliver valuable software efficiently and effectively.

What is the role of a Scrum Master in Agile development?
The Scrum Master is a facilitator and coach in Agile development. Their primary role is to ensure that the Scrum team follows the Agile principles and Scrum framework effectively. They remove obstacles, promote communication, and help the team achieve their goals, fostering a collaborative and efficient development environment.

What are the key differences between verification and validation in the SDLC context?
Verification: Focuses on ensuring that the software is built correctly, adhering to its specified requirements and design. It involves reviews, inspections, and walkthroughs to check for errors and compliance.

Validation: Focuses on ensuring that the software meets the customer's actual needs and expectations. It involves testing the software to ensure it functions as intended and satisfies the user's requirements.

What is the V-model.
The V-model is a software development model that emphasizes a strong relationship between each development phase and its corresponding testing phase. It is called the "V-model" because of its V-shaped representation, where the development and testing phases are shown to be mirror images of each other. In this model, each development stage is associated with a testing phase, ensuring that requirements are properly validated and verified throughout the development process. The V-model helps to catch defects early and promotes a systematic approach to software development and testing.

What is RAD?
RAD stands for Rapid Application Development in SDLC. It is a software development methodology that emphasizes quick prototyping and iterative development to accelerate the application development process. RAD focuses on user involvement, feedback, and collaboration between developers and clients to deliver software solutions more rapidly and efficiently.


Operating System [OS]

What is an operating system?
An operating system is software that acts as an intermediary between users and computer hardware. It manages computer resources, provides a user interface, and enables the execution of applications and tasks on a computer system.

What are the different types of operating systems?

  1. Single-User, Single-Tasking OS: Supports only one user and allows running a single task at a time.

  2. Single-User, Multi-Tasking OS: Allows a single user to run multiple tasks simultaneously.

  3. Multi-User OS: Supports multiple users running multiple tasks concurrently.

  4. Real-Time OS: Prioritizes tasks to meet strict timing constraints for time-sensitive applications.

  5. Batch OS: Executes tasks in batches without user interaction.

  6. Time-Sharing OS: Shares CPU time among multiple users in short time slices.

  7. Distributed OS: Manages networked computers as a single system.

  8. Embedded OS: Designed for specific devices or embedded systems with limited resources.

  9. Mobile OS: Developed for smartphones and mobile devices.

  10. Virtualization OS: Hosts multiple virtual machines on a single physical machine.

What is the difference between a multiprogramming and multitasking operating system?
Multiprogramming and multitasking are often used interchangeably, but there is a subtle difference between the two:

Multiprogramming Operating System:

  • Involves running multiple programs simultaneously by dividing CPU time into small slices and switching between them.

  • Each program gets a short burst of CPU time before being switched out, allowing for overlapping execution.

  • Goal: To maximize CPU utilization and keep the CPU busy at all times.

Multitasking Operating System:

  • Involves executing multiple tasks or processes concurrently on a single CPU.

  • The CPU switches between tasks quickly, giving users the illusion of running tasks simultaneously.

  • Goal: To improve user experience and responsiveness by allowing efficient task switching.

In summary, multiprogramming focuses on keeping the CPU busy by interleaving small slices of different programs, while multitasking emphasizes efficient task switching to provide a responsive user experience.

Explain the concept of virtual memory?

Virtual memory is a memory management technique used by modern operating systems to provide the illusion of having more RAM (Random Access Memory) than physically available. It allows processes to use more memory than is physically installed in the system.

In virtual memory, each process has its own separate address space, and the memory addresses used by the processes are virtual. These virtual addresses are translated into physical addresses by the hardware and the operating system.

Describe the difference between a process and a thread.
A process is an independent unit of execution with its own memory space, whereas a thread is a smaller unit of execution within a process that shares the same memory space. Processes are heavyweight, while threads are lightweight.

What is Deadlock in operating systems?
Deadlock in operating systems is a situation where two or more processes are unable to proceed with their execution because each process is waiting for a resource that is held by another process in the same group, resulting in a circular waiting dependency. As a result, none of the processes can make progress, leading to a standstill in the system's operation.

How do you prevent deadlock in an operating system? Explain deadlock avoidance and deadlock detection.

  1. Deadlock Prevention:

    • Deadlock prevention involves structuring the system in a way that makes it impossible for deadlocks to occur.

    • Techniques like resource allocation policies, resource ordering, and ensuring a single instance of resource allocation can be used to prevent deadlocks.

    • However, prevention may lead to resource underutilization and may not always be feasible.

  2. Deadlock Avoidance:

    • Deadlock avoidance involves dynamically analyzing the resource allocation to avoid potential deadlocks.

    • It employs algorithms like Banker's algorithm to determine if a resource allocation request can lead to a deadlock.

    • Resources are allocated only if the system remains in a safe state after the allocation.

    • It ensures better resource utilization, but it requires advance knowledge of resource needs.

  3. Deadlock Detection:

    • Deadlock detection involves periodically checking the system for deadlock occurrence.

    • Resource allocation graphs or other algorithms can be used to detect cycles in resource allocation.

    • Once a deadlock is detected, the system can take corrective actions like process termination or resource preemption to resolve the deadlock.

What are the various process states in a process life cycle?
The various process states in a process life cycle are:

  1. New: The process is being created but not yet ready for execution.

  2. Ready: The process is prepared to run and is waiting for CPU time.

  3. Running: The process is currently being executed by the CPU.

  4. Blocked (Wait): The process is unable to proceed and is waiting for an event (e.g., I/O) to complete.

  5. Terminated: The process has finished its execution and has been terminated, either voluntarily or forcefully.

What is thrashing?
Thrashing is a situation in a virtual memory system where the majority of the time is spent swapping data between main memory and disk, instead of executing actual instructions. It occurs when the system is constantly trying to load and evict pages from memory, leading to a significant decrease in performance.

What is a page fault?
A page fault is a type of exception that occurs in computer systems with virtual memory when a process attempts to access a page of memory that is currently not in the main physical memory (RAM). The operating system then handles this exception by fetching the required page from secondary storage (such as the hard disk) into RAM, allowing the process to proceed with its execution.

Describe the role of the memory manager in an operating system.
The memory manager in an operating system is responsible for allocating and deallocating memory resources to processes, ensuring efficient memory utilization, and handling memory protection to prevent unauthorized access to memory locations.

What is kernel?
The kernel is the core part of an operating system that acts as a bridge between software applications and the computer hardware. It manages system resources, controls hardware access, and enables communication between software and hardware components.

Explain the role of the I/O manager in an operating system.
The I/O manager in an operating system is responsible for coordinating and managing Input/Output (I/O) operations between the CPU, memory, and peripheral devices. It handles the communication and data transfer to ensure efficient utilization of resources and smooth functioning of the system.


Computer Networks

Differentiate between a hub, switch, and router.
Here's the differentiation between a hub, switch, and router:

  1. Hub:

    • Operates at the physical layer (Layer 1) of the OSI model.

    • Broadcasts incoming data to all connected devices on the network.

    • Provides no intelligence and does not filter or manage network traffic.

    • Inefficient for larger networks due to unnecessary data collisions and bandwidth wastage.

  2. Switch:

    • Operates at the data link layer (Layer 2) of the OSI model.

    • Efficiently forwards data only to the intended recipient based on MAC addresses.

    • Creates dedicated communication channels between devices, reducing data collisions.

    • Manages network traffic using MAC address tables for faster data transmission.

  3. Router:

    • Operates at the network layer (Layer 3) of the OSI model.

    • Connects multiple networks and directs data packets between them.

    • Uses IP addresses to determine the best path for data to reach its destination.

    • Provides network segmentation, enhancing security and efficiency.

Explain the OSI.
The OSI (Open Systems Interconnection) model is a conceptual framework that standardizes network communication into seven distinct layers. Each layer serves a specific function and interacts with the layers above and below it. The model promotes interoperability between different network technologies and allows for easier development and troubleshooting of network protocols and applications.

What is the TCP/IP model?
The TCP/IP model is a networking framework used for communication between devices over the internet. It consists of four layers:

  1. Application Layer: Provides network services directly to applications, such as email, web browsing, and file transfer. Examples of protocols in this layer include HTTP, FTP, SMTP.

  2. Transport Layer: Manages end-to-end communication between devices. It ensures data delivery, flow control, and error detection. Notable protocols in this layer are TCP (Transmission Control Protocol) and UDP (User Datagram Protocol).

  3. Internet Layer: Handles the routing of data packets across networks and provides logical addressing through IP (Internet Protocol).

  4. Link Layer: Deals with the physical transmission of data over the local network. It includes protocols like Ethernet and Wi-Fi.

Describe the key differences between IPv4 and IPv6.
Key differences between IPv4 and IPv6:

  1. Address Length:

    • IPv4 uses 32-bit addresses, limiting it to approximately 4.3 billion unique addresses.

    • IPv6 uses 128-bit addresses, providing an astronomically larger address space of approximately 340 undecillion unique addresses.

  2. Address Configuration:

    • IPv4 addresses are typically assigned statically or dynamically using DHCP (Dynamic Host Configuration Protocol).

    • IPv6 addresses can be automatically assigned using stateless address auto-configuration (SLAAC) or manually assigned.

  3. Security:

    • IPv4 lacks built-in security features, making it more susceptible to certain attacks.

    • IPv6 incorporates IPSec (Internet Protocol Security) as a mandatory part of the protocol suite, providing enhanced security.

What is subnetting?
Subnetting is the process of dividing a larger network into smaller sub-networks, known as subnets. It helps optimize network performance, manage IP addresses efficiently, and enhance security by grouping devices with similar requirements together. Subnetting is a fundamental concept in IP networking, allowing for more efficient use of available IP address space and facilitating better network organization and management.

What is DNS?
DNS stands for Domain Name System. It is a fundamental technology used on the internet to translate human-readable domain names (like www.example.com) into numerical IP addresses (such as 192.0.2.1) that computers can understand. DNS acts like a phonebook of the internet, enabling users to access websites and services using easy-to-remember domain names rather than complex IP addresses.

Define MAC address and IP address.
MAC address (Media Access Control address): A unique identifier assigned to a network interface card (NIC) in a device. It is used for communication within a local network and ensures data is delivered to the correct device on the same network.

IP address (Internet Protocol address): A numeric label assigned to each device connected to a network using the Internet Protocol. It enables devices to be identified and located on a network, allowing data to be routed and transmitted across the internet.

What is the meaning of 10Base-T?
It is used to specify the data transfer rate. In 10Base-T, 10 specify the data transfer rate, i.e., 10Mbps. The word Base specifies the baseband as opposed to broadband. T specifies the type of cable which is a twisted pair.

What is DHCP?
DHCP stands for "Dynamic Host Configuration Protocol." It is a network protocol that automatically assigns IP addresses and other network configuration information to devices within a network. This allows devices to join a network and obtain the necessary network settings without manual configuration, making network setup and management more efficient.

Differentiate between half-duplex and full-duplex communication.
Half-duplex communication: In half-duplex communication, data can be transmitted in both directions, but not simultaneously. Devices take turns sending and receiving data, like a walkie-talkie, where one party talks while the other listens.

Full-duplex communication: In full-duplex communication, data can be transmitted in both directions simultaneously. Devices can send and receive data simultaneously, similar to a telephone conversation where both parties can talk and listen at the same time.

What is the purpose of a firewall?
The purpose of a firewall is to act as a security barrier between a private internal network and the outside internet or other untrusted networks. It helps to monitor and control incoming and outgoing network traffic based on predetermined security rules, preventing unauthorized access and protecting the internal network from potential threats and attacks.

What is a VPN?
A VPN (Virtual Private Network) is a secure and encrypted connection that allows users to access the internet or a private network from a remote location, ensuring privacy, anonymity, and data security.

Explain the concept of bandwidth in networking.
Every signal has a limit of upper range frequency and lower range frequency. The range of limit of the network between its upper and lower frequency is called bandwidth.

What is Star topology in computer networks?
Star topology is a type of network topology used in computer networks. In this configuration, all network devices are connected to a central hub or switch through individual point-to-point links. The central hub acts as a central connection point for all the devices in the network.

What is a node and link?
A network is a connection setup of two or more computers directly connected by some physical mediums like optical fiber or coaxial cable. This physical medium of connection is known as a link, and the computers that it is connected are known as nodes.


Coding Questions and Solutions

Reverse a String: Write a function to reverse a given string. (e.g., "hello" -> "olleh")

public class StringReversal {
    public static String reverseString(String input) {
        char[] charArray = input.toCharArray();
        int left = 0;
        int right = input.length() - 1;

        while (left < right) {
            char temp = charArray[left];
            charArray[left] = charArray[right];
            charArray[right] = temp;

            left++;
            right--;
        }

        return new String(charArray);
    }

    public static void main(String[] args) {
        String inputString = "hello";
        String reversedString = reverseString(inputString);
        System.out.println("Reversed String: " + reversedString);
    }
}

Print numbers from 1 to 100 without using any loop.

public class PrintNumbersWithoutLoop {

    public static void main(String[] args) {
        printNumbers(1);
    }

    public static void printNumbers(int n) {
        if (n <= 100) {
            System.out.println(n);
            printNumbers(n + 1);
        }
    }
}

Swap two numbers without using a third variable.

public class SwapNumbers {

    public static void main(String[] args) {
        int num1 = 5;
        int num2 = 10;

        System.out.println("Before swapping:");
        System.out.println("num1 = " + num1);
        System.out.println("num2 = " + num2);

        // Swap the numbers without using a third variable
        num1 = num1 + num2;
        num2 = num1 - num2;
        num1 = num1 - num2;

        System.out.println("\nAfter swapping:");
        System.out.println("num1 = " + num1);
        System.out.println("num2 = " + num2);
    }
}

Print the second-highest element of an array.

public class SecondHighestElement {

    public static void main(String[] args) {
        int[] arr = {10, 5, 20, 8, 15, 12};

        int secondHighest = findSecondHighest(arr);

        if (secondHighest != Integer.MIN_VALUE) {
            System.out.println("Second highest element: " + secondHighest);
        } else {
            System.out.println("Array does not have a second highest element.");
        }
    }

    public static int findSecondHighest(int[] arr) {
        int highest = Integer.MIN_VALUE;
        int secondHighest = Integer.MIN_VALUE;

        for (int num : arr) {
            if (num > highest) {
                secondHighest = highest;
                highest = num;
            } else if (num > secondHighest && num != highest) {
                secondHighest = num;
            }
        }

        return secondHighest;
    }
}

Check whether a given number is prime or not.

import java.util.Scanner;

public class PrimeNumberChecker {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a number to check if it's prime: ");
        int number = scanner.nextInt();

        boolean isPrime = isPrimeNumber(number);

        if (isPrime) {
            System.out.println(number + " is a prime number.");
        } else {
            System.out.println(number + " is not a prime number.");
        }

        scanner.close();
    }

    public static boolean isPrimeNumber(int number) {
        if (number <= 1) {
            return false;
        }

        // Optimized loop: check divisors up to the square root of the number
        for (int i = 2; i <= Math.sqrt(number); i++) {
            if (number % i == 0) {
                return false;
            }
        }

        return true;
    }
}

Implement the binary search algorithm to find the index of a given element in a sorted array.

public class BinarySearch {
    // Binary search function
    public static int binarySearch(int[] arr, int target) {
        int left = 0;
        int right = arr.length - 1;

        while (left <= right) {
            int mid = left + (right - left) / 2;

            // If the target is found, return the index
            if (arr[mid] == target) {
                return mid;
            }
            // If the target is greater than the middle element, search the right half
            else if (arr[mid] < target) {
                left = mid + 1;
            }
            // If the target is smaller than the middle element, search the left half
            else {
                right = mid - 1;
            }
        }

        // If the target is not found, return -1
        return -1;
    }

    public static void main(String[] args) {
        int[] sortedArray = { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19 };
        int target = 11;
        int index = binarySearch(sortedArray, target);

        if (index != -1) {
            System.out.println("Element found at index: " + index);
        } else {
            System.out.println("Element not found in the array.");
        }
    }
}

Check for Palindrome: Write a function to check if a given string is a palindrome. (e.g., "racecar" -> True, "hello" -> False)

public class PalindromeChecker {
    public static boolean isPalindrome(String str) {
        int left = 0;
        int right = str.length() - 1;

        while (left < right) {
            if (str.charAt(left) != str.charAt(right)) {
                return false;
            }
            left++;
            right--;
        }

        return true;
    }

    public static void main(String[] args) {
        String str1 = "racecar";
        String str2 = "hello";
        System.out.println(str1 + " is a palindrome? " + isPalindrome(str1));
        System.out.println(str2 + " is a palindrome? " + isPalindrome(str2));
    }
}

Find the Maximum Subarray Sum: Given an array of integers, find the contiguous subarray with the largest sum. (e.g., [-2, 1, -3, 4, -1, 2, 1, -5, 4] -> Maximum subarray sum: 6)

public class MaximumSubarraySum {
    public static int maxSubarraySum(int[] nums) {
        if (nums == null || nums.length == 0) {
            throw new IllegalArgumentException("Input array is null or empty.");
        }

        int maxSum = nums[0];
        int currentSum = nums[0];

        for (int i = 1; i < nums.length; i++) {
            // Choose the larger between the current element and the current sum + current element
            currentSum = Math.max(nums[i], currentSum + nums[i]);

            // Update the maximum sum seen so far
            maxSum = Math.max(maxSum, currentSum);
        }

        return maxSum;
    }

    public static void main(String[] args) {
        int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
        int result = maxSubarraySum(nums);
        System.out.println("Maximum subarray sum: " + result); // Output: Maximum subarray sum: 6
    }
}

Find the unique characters in a String. (Eg. Hello, Output: H, e, o)

import java.util.HashSet;

public class UniqueCharactersFinder {
    public static void main(String[] args) {
        String inputString = "Hello";
        String uniqueCharacters = findUniqueCharacters(inputString);
        System.out.println("Unique characters in the input string: " + uniqueCharacters);
    }

    public static String findUniqueCharacters(String input) {
        HashSet<Character> uniqueChars = new HashSet<>();
        StringBuilder result = new StringBuilder();

        for (char c : input.toCharArray()) {
            if (!uniqueChars.contains(c)) {
                uniqueChars.add(c);
                result.append(c);
            }
        }

        return result.toString();
    }
}

Check for Anagrams: Write a function to check if two strings are anagrams of each other. (e.g., "listen" and "silent" are anagrams)

import java.util.Arrays;

public class AnagramChecker {

    public static boolean areAnagrams(String str1, String str2) {
        // Remove any spaces and convert both strings to lowercase for case-insensitive comparison
        str1 = str1.replaceAll("\\s", "").toLowerCase();
        str2 = str2.replaceAll("\\s", "").toLowerCase();

        // If the lengths of the strings are different, they cannot be anagrams
        if (str1.length() != str2.length()) {
            return false;
        }

        // Convert strings to char arrays and sort them
        char[] charArray1 = str1.toCharArray();
        char[] charArray2 = str2.toCharArray();
        Arrays.sort(charArray1);
        Arrays.sort(charArray2);

        // Compare the sorted arrays
        return Arrays.equals(charArray1, charArray2);
    }

    public static void main(String[] args) {
        String str1 = "listen";
        String str2 = "silent";
        if (areAnagrams(str1, str2)) {
            System.out.println(str1 + " and " + str2 + " are anagrams.");
        } else {
            System.out.println(str1 + " and " + str2 + " are not anagrams.");
        }
    }
}

Fibonacci Series: Write code to generate the Fibonacci series up to a given number N.

import java.util.Scanner;

public class FibonacciSeries {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the value of N: ");
        int N = scanner.nextInt();

        System.out.println("Fibonacci series up to N:");
        generateFibonacciSeries(N);

        scanner.close();
    }

    public static void generateFibonacciSeries(int N) {
        int first = 0;
        int second = 1;

        System.out.print(first + " ");

        while (second <= N) {
            System.out.print(second + " ");
            int next = first + second;
            first = second;
            second = next;
        }
    }
}

Bubble Sort: Implement the bubble sort algorithm to sort an array of integers.

import java.util.Arrays;

public class BubbleSort {

    public static void main(String[] args) {
        int[] arr = {64, 34, 25, 12, 22, 11, 90};

        System.out.println("Original Array: " + Arrays.toString(arr));

        bubbleSort(arr);

        System.out.println("Sorted Array: " + Arrays.toString(arr));
    }

    public static void bubbleSort(int[] arr) {
        int n = arr.length;

        for (int i = 0; i < n - 1; i++) {
            // Set a flag to check if any swaps are made in this pass
            boolean swapped = false;

            // Last i elements are already in place, so no need to check them again
            for (int j = 0; j < n - i - 1; j++) {
                // Swap if the element found is greater than the next element
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    swapped = true;
                }
            }

            // If no two elements were swapped in this pass, the array is already sorted
            if (!swapped) {
                break;
            }
        }
    }
}

Reverse a Linked List: Write a function to reverse a linked list.

class ListNode {
    int val;
    ListNode next;

    ListNode(int val) {
        this.val = val;
        this.next = null;
    }
}

public class ReverseLinkedList {

    public ListNode reverse(ListNode head) {
        if (head == null || head.next == null) {
            return head; // If the list is empty or has only one node, it is already reversed.
        }

        ListNode prev = null;
        ListNode current = head;
        ListNode next = null;

        while (current != null) {
            next = current.next; // Store the next node.
            current.next = prev; // Reverse the link by pointing the current node to the previous node.

            // Move prev and current pointers one step forward.
            prev = current;
            current = next;
        }

        return prev; // The new head of the reversed list will be the last node, which is now 'prev'.
    }
}

Check for Balanced Parentheses: Write a function to check if a given expression has balanced parentheses.

import java.util.Stack;

public class BalancedParenthesesChecker {

    public static void main(String[] args) {
        String expression1 = "{[()]()}"; // Balanced expression
        String expression2 = "((())";   // Unbalanced expression

        System.out.println(expression1 + " is balanced: " + isBalanced(expression1));
        System.out.println(expression2 + " is balanced: " + isBalanced(expression2));
    }

    public static boolean isBalanced(String expression) {
        Stack<Character> stack = new Stack<>();

        for (int i = 0; i < expression.length(); i++) {
            char currentChar = expression.charAt(i);

            if (currentChar == '(' || currentChar == '[' || currentChar == '{') {
                stack.push(currentChar);
            } else if (currentChar == ')' || currentChar == ']' || currentChar == '}') {
                if (stack.isEmpty()) {
                    return false; // Unbalanced: Closing parenthesis without an opening one
                } else {
                    char topChar = stack.pop();
                    if ((currentChar == ')' && topChar != '(')
                            || (currentChar == ']' && topChar != '[')
                            || (currentChar == '}' && topChar != '{')) {
                        return false; // Unbalanced: Mismatched opening and closing parentheses
                    }
                }
            }
        }

        return stack.isEmpty(); // Balanced if the stack is empty after processing the whole expression
    }
}

Longest Common Subsequence: Given two strings, find the length of their longest common subsequence.

public class LongestCommonSubsequence {

    public static int findLCSLength(String str1, String str2) {
        int m = str1.length();
        int n = str2.length();

        int[][] dp = new int[m + 1][n + 1];

        for (int i = 0; i <= m; i++) {
            for (int j = 0; j <= n; j++) {
                if (i == 0 || j == 0)
                    dp[i][j] = 0;
                else if (str1.charAt(i - 1) == str2.charAt(j - 1))
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                else
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
            }
        }

        return dp[m][n];
    }

    public static void main(String[] args) {
        String str1 = "AGGTAB";
        String str2 = "GXTXAYB";

        int lcsLength = findLCSLength(str1, str2);
        System.out.println("Length of Longest Common Subsequence: " + lcsLength);
    }
}

Merge Two Sorted Arrays: Given two sorted arrays, merge them into a single sorted array.

public class MergeSortedArrays {

    public static void main(String[] args) {
        int[] arr1 = {1, 3, 5, 7};
        int[] arr2 = {2, 4, 6, 8, 10};

        int[] mergedArray = mergeArrays(arr1, arr2);

        System.out.println("Merged sorted array:");
        for (int num : mergedArray) {
            System.out.print(num + " ");
        }
    }

    public static int[] mergeArrays(int[] arr1, int[] arr2) {
        int n1 = arr1.length;
        int n2 = arr2.length;
        int[] mergedArray = new int[n1 + n2];

        int i = 0, j = 0, k = 0;

        // Compare elements of both arrays and add the smaller one to the mergedArray
        while (i < n1 && j < n2) {
            if (arr1[i] < arr2[j]) {
                mergedArray[k] = arr1[i];
                i++;
            } else {
                mergedArray[k] = arr2[j];
                j++;
            }
            k++;
        }

        // Add any remaining elements from arr1, if any
        while (i < n1) {
            mergedArray[k] = arr1[i];
            i++;
            k++;
        }

        // Add any remaining elements from arr2, if any
        while (j < n2) {
            mergedArray[k] = arr2[j];
            j++;
            k++;
        }

        return mergedArray;
    }
}

Check out my campus placement experience blogs,

Did you find this article valuable?

Support Abhishek Sharma by becoming a sponsor. Any amount is appreciated!