Computer Science

Computer Science

Top Interview Questions

About Computer Science

 

Computer Science: An Overview

Computer Science (CS) is the study of computers and computational systems. Unlike electrical and computer engineers, computer scientists focus primarily on software and software systems; this includes their theory, design, development, and application. As a discipline, computer science combines both theoretical foundations and practical techniques to solve problems using computers. It plays a central role in the modern world, impacting fields ranging from business and healthcare to entertainment, artificial intelligence, and cybersecurity.

History and Evolution of Computer Science

The origins of computer science can be traced back to the development of early computational devices and theoretical models. In the 19th century, Charles Babbage designed the Analytical Engine, a mechanical general-purpose computer, while Ada Lovelace wrote what is considered the first algorithm intended to be processed by a machine. However, the formal development of computer science as a discipline began in the 20th century.

During World War II, the need for fast calculations led to the creation of early electronic computers like the ENIAC (Electronic Numerical Integrator and Computer). In the 1950s, programming languages such as Fortran and COBOL emerged, allowing computers to be used for scientific and business applications. The 1960s and 1970s saw the rise of algorithms, data structures, and operating systems, forming the core theoretical foundation of modern computer science. Over time, the discipline expanded to include areas such as artificial intelligence, database systems, networking, human-computer interaction, and cybersecurity.

Core Areas of Computer Science

Computer science is a broad field, encompassing various areas of study. The key areas include:

  1. Algorithms and Data Structures:
    Algorithms are step-by-step procedures for solving problems, while data structures are ways of organizing and storing data efficiently. Together, they form the backbone of computer science, influencing the efficiency and effectiveness of software and applications. Understanding algorithms and data structures is essential for solving complex computational problems and is a key focus in software development and research.

  2. Programming Languages:
    Programming languages are formal languages used to write software. Popular languages include Python, Java, C++, and JavaScript. Each language has its strengths and applications. For instance, Python is favored in data science and artificial intelligence, while C++ is often used for system-level programming and high-performance applications. Learning programming languages is fundamental for translating computational problems into executable programs.

  3. Software Engineering:
    Software engineering involves the systematic design, development, testing, and maintenance of software systems. It emphasizes principles such as modularity, scalability, reliability, and maintainability. Techniques like agile development, version control, and continuous integration have transformed software engineering into a structured and collaborative discipline, allowing teams to build complex systems efficiently.

  4. Computer Architecture and Systems:
    This area deals with the internal organization of computers, including processors, memory, storage, and networking components. Understanding computer architecture helps optimize software performance and develop efficient systems. Additionally, operating systems play a crucial role by managing hardware resources and providing a platform for application execution.

  5. Artificial Intelligence (AI) and Machine Learning (ML):
    AI is the study of creating systems that can perform tasks requiring human intelligence, such as reasoning, learning, problem-solving, and decision-making. Machine learning, a subset of AI, involves developing algorithms that enable computers to learn from data. Applications of AI and ML range from voice assistants and autonomous vehicles to medical diagnosis and financial predictions.

  6. Databases and Information Systems:
    Databases store, organize, and manage large amounts of data. Database management systems (DBMS) like MySQL, Oracle, and MongoDB provide tools for efficient data storage, retrieval, and manipulation. Information systems integrate databases with applications to support business processes, decision-making, and analytics.

  7. Networking and Communication:
    Computer networks connect devices to share information and resources. Networking involves protocols, architectures, and technologies that ensure reliable and secure data communication. The Internet, cloud computing, and distributed systems are essential components of modern networking, enabling global connectivity and large-scale applications.

  8. Cybersecurity:
    With the increasing reliance on digital systems, protecting information and systems from cyber threats has become critical. Cybersecurity involves implementing measures to prevent unauthorized access, data breaches, and cyberattacks. Techniques include encryption, firewalls, intrusion detection systems, and ethical hacking.

  9. Human-Computer Interaction (HCI):
    HCI focuses on designing user-friendly interfaces and interactions between humans and computers. It involves understanding user behavior, ergonomics, and usability principles. Applications include web design, mobile apps, virtual reality, and gaming.

Applications of Computer Science

The applications of computer science are vast and touch almost every aspect of modern life. Some notable areas include:

  • Healthcare: Computer science enables advanced medical imaging, patient data management, telemedicine, and AI-based diagnostic tools. Machine learning models can predict disease outbreaks, personalize treatments, and analyze genetic data.

  • Business and Finance: Companies use computer systems for automation, data analytics, financial modeling, and e-commerce. Algorithms optimize supply chains, detect fraud, and provide personalized customer experiences.

  • Education: Computer-based learning platforms, virtual classrooms, and adaptive learning systems enhance education quality. Artificial intelligence helps provide personalized learning experiences and assess student performance.

  • Entertainment: Computer science drives video games, animation, virtual reality, and digital media production. Graphics algorithms, AI-based character behaviors, and streaming technologies have transformed the entertainment industry.

  • Science and Research: High-performance computing, simulations, and data analysis tools enable researchers to study complex phenomena in physics, biology, climate science, and engineering.

  • Transportation: Autonomous vehicles, traffic management systems, and logistics planning rely heavily on algorithms, sensors, and AI.

Importance of Computer Science in Modern Society

Computer science has become a cornerstone of technological progress and economic growth. Its importance can be highlighted in several ways:

  1. Problem-Solving: Computer science equips individuals with analytical and computational skills to solve real-world problems efficiently. From optimizing business operations to modeling scientific phenomena, it provides tools and methods for innovation.

  2. Job Opportunities: The demand for skilled computer scientists continues to rise globally. Careers range from software developers, data scientists, and AI specialists to cybersecurity analysts and systems architects. Knowledge of computer science enhances employability across industries.

  3. Innovation and Research: Advances in computer science drive innovation in artificial intelligence, robotics, cloud computing, quantum computing, and biotechnology. Research in algorithms, machine learning, and human-computer interaction pushes the boundaries of what technology can achieve.

  4. Digital Transformation: Computer science enables the digitization of industries, governments, and daily life. It facilitates the creation of smart cities, digital healthcare systems, and automated financial services.

Future of Computer Science

The future of computer science is promising, with emerging technologies poised to transform society further. Key trends include:

  • Quantum Computing: Leveraging the principles of quantum mechanics, quantum computers have the potential to solve problems in seconds that would take classical computers millennia.

  • Artificial Intelligence: AI continues to evolve, with advancements in deep learning, natural language processing, and autonomous systems reshaping industries and daily life.

  • Internet of Things (IoT): Connecting billions of devices to collect and analyze data will revolutionize smart homes, industrial automation, and healthcare monitoring.

  • Cybersecurity and Privacy: As data becomes more integral, developing robust security and privacy solutions will be crucial to protect information and maintain trust.

  • Sustainable Computing: Green computing practices aim to reduce the environmental impact of data centers, computational devices, and energy-intensive processes.

Fresher Interview Questions

 

1. What is Computer Science?

Answer:
Computer Science is the study of computers and computational systems. It focuses on the theory, design, development, and application of software and systems. It includes topics like programming, algorithms, data structures, databases, networking, artificial intelligence, and more.


2. What is an Algorithm?

Answer:
An algorithm is a step-by-step procedure or formula for solving a problem. It’s a sequence of instructions that tells the computer how to perform a specific task.
Example: Sorting numbers in ascending order is done using sorting algorithms like Bubble Sort, Quick Sort, or Merge Sort.


3. What is the difference between Compiler and Interpreter?

Answer:

Feature Compiler Interpreter
Converts code Converts entire source code to machine code Converts and executes code line by line
Speed Faster execution Slower execution
Error detection Shows errors after compilation Shows errors line by line
Example C, C++ Python, Ruby

4. What is a Data Structure?

Answer:
A data structure is a way of organizing and storing data to perform operations efficiently. Common data structures include:

  • Array: Collection of elements of same type stored in contiguous memory.

  • Linked List: Sequence of nodes, each containing data and a pointer to the next node.

  • Stack: Last-In-First-Out (LIFO) structure.

  • Queue: First-In-First-Out (FIFO) structure.

  • Tree/Graph: Hierarchical and network-based structures.


5. What is Object-Oriented Programming (OOP)?

Answer:
OOP is a programming paradigm based on objects that contain data (attributes) and methods (functions).
Key concepts:

  • Class: Blueprint of an object.

  • Object: Instance of a class.

  • Inheritance: Child class inherits properties of parent class.

  • Polymorphism: Ability to take multiple forms (overloading and overriding).

  • Encapsulation: Wrapping data and methods in a single unit.

  • Abstraction: Hiding internal details and showing functionality only.


6. Difference between Stack and Queue

Answer:

Feature Stack Queue
Principle LIFO (Last In First Out) FIFO (First In First Out)
Operations push(), pop() enqueue(), dequeue()
Example Undo functionality Print Queue

7. What is a Database?

Answer:
A database is an organized collection of data, stored and accessed electronically. Databases are managed using DBMS (Database Management System).
Types of Databases:

  • Relational Database: Data is stored in tables (e.g., MySQL, Oracle).

  • Non-Relational Database: Data is stored as key-value pairs, documents, etc. (e.g., MongoDB, Redis).


8. What is SQL?

Answer:
SQL (Structured Query Language) is used to communicate with a database to perform operations such as:

  • SELECT: Retrieve data

  • INSERT: Add data

  • UPDATE: Modify data

  • DELETE: Remove data


9. What is the difference between HTTP and HTTPS?

Answer:

Feature HTTP HTTPS
Security Not secure Secure (uses SSL/TLS)
Port 80 443
Data Sent in plaintext Encrypted
Use Simple websites Banking, e-commerce

10. Explain the OSI Model

Answer:
OSI (Open Systems Interconnection) model is a conceptual framework used to understand network interactions. It has 7 layers:

  1. Physical – Transmission of raw bits (Cables, Hubs).

  2. Data Link – Error detection, MAC addressing (Switches).

  3. Network – Routing and logical addressing (IP).

  4. Transport – Reliable transmission (TCP/UDP).

  5. Session – Manages sessions between applications.

  6. Presentation – Data translation, encryption, compression.

  7. Application – End-user services (HTTP, FTP).


11. Difference between Process and Thread

Answer:

Feature Process Thread
Definition Program in execution Lightweight subprocess within a process
Memory Separate memory space Shares memory of process
Communication Inter-process communication needed Direct communication using shared memory
Overhead Higher Lower

12. What is Big O Notation?

Answer:
Big O Notation measures the efficiency of an algorithm in terms of time complexity or space complexity.

  • O(1): Constant time

  • O(n): Linear time

  • O(n²): Quadratic time

  • O(log n): Logarithmic time


13. Explain Recursion

Answer:
Recursion is a process where a function calls itself directly or indirectly to solve a smaller version of the problem.
Example: Factorial of n:

int factorial(int n) {
    if(n == 0) return 1;
    else return n * factorial(n-1);
}

14. What is a Programming Language?

Answer:
A programming language is a formal set of instructions used to communicate with a computer.
Types:

  • Low-Level Language: Close to machine code (Assembly).

  • High-Level Language: Easy to read/write (Python, Java, C++).


15. Difference between Static and Dynamic Memory Allocation

Answer:

Feature Static Dynamic
Allocation Time Compile-time Run-time
Size Fixed Flexible
Example Arrays Linked List, malloc() in C

16. What is Git?

Answer:
Git is a version control system used to track changes in source code during software development.
Key Commands:

  • git init – Initialize repository

  • git clone – Copy repository

  • git add – Stage changes

  • git commit – Save changes

  • git push – Upload changes to remote repository


17. What is Cloud Computing?

Answer:
Cloud Computing provides on-demand computing resources (servers, storage, databases, networking) over the internet.
Types:

  • IaaS (Infrastructure as a Service)

  • PaaS (Platform as a Service)

  • SaaS (Software as a Service)


18. What is Machine Learning?

Answer:
Machine Learning is a subset of AI where systems learn from data to make predictions without being explicitly programmed.
Types:

  • Supervised Learning – Labeled data

  • Unsupervised Learning – Unlabeled data

  • Reinforcement Learning – Learning via rewards


19. What is the difference between AI, ML, and DL?

Answer:

Feature AI ML DL
Definition Broad concept of machines simulating human intelligence Subset of AI using data to learn Subset of ML using neural networks
Example Chess-playing robot Predicting house prices Image recognition

20. What is the difference between HTTP GET and POST?

Answer:

Feature GET POST
Data visibility Appended to URL Hidden in request body
Use Fetch data Send data
Security Less secure More secure
Caching Can be cached Cannot be cached

21. What is a Linked List?

Answer:
A linked list is a linear data structure where each element (node) contains:

  • Data – The value stored

  • Pointer – Reference to the next node

Types:

  1. Singly Linked List – Each node points to the next node.

  2. Doubly Linked List – Each node points to the next and previous node.

  3. Circular Linked List – Last node points back to the first node.

Example:

struct Node {
    int data;
    struct Node* next;
};

22. What is a Binary Tree?

Answer:
A binary tree is a hierarchical data structure where each node has at most 2 children (left and right).

Special Types:

  • Binary Search Tree (BST) – Left child < root < right child

  • Complete Binary Tree – All levels filled except possibly last

  • Full Binary Tree – Every node has 0 or 2 children


23. Explain Hashing.

Answer:
Hashing is a technique to store and retrieve data efficiently using a hash function. It converts a key into an index in a hash table.

Example:
If key = 45, hash function = key % 10 → Index = 5.

Collision Handling:

  • Chaining – Linked list at each index

  • Open Addressing – Find next empty slot


24. What is Deadlock in OS?

Answer:
Deadlock occurs when two or more processes wait for each other indefinitely.

Necessary Conditions:

  1. Mutual exclusion

  2. Hold and wait

  3. No preemption

  4. Circular wait

Prevention: Avoid at least one of the above conditions.


25. What is Paging in OS?

Answer:
Paging is a memory management scheme that eliminates fragmentation by dividing memory into fixed-size blocks called pages (logical memory) and frames (physical memory).

Example: Page size = 4KB → Process with 12KB → 3 pages


26. Difference between Process and Program

Feature Process Program
Definition A program in execution A set of instructions
State Active Passive
Memory Allocated Not allocated
Example Running Chrome Chrome.exe file

27. Explain Virtual Memory

Answer:
Virtual memory allows a system to use more memory than physically available by using a portion of the hard disk as RAM.

Benefits:

  • Multitasking

  • Running large programs

  • Efficient memory utilization


28. What is Normalization in DBMS?

Answer:
Normalization organizes a database to reduce redundancy and improve integrity.

Normal Forms:

  1. 1NF – No repeating groups

  2. 2NF – No partial dependency

  3. 3NF – No transitive dependency

  4. BCNF – Stronger form of 3NF

Example:
Before 1NF: Multiple phone numbers in one column.
After 1NF: Separate rows for each number.


29. What is a Primary Key and Foreign Key?

Answer:

  • Primary Key: Unique identifier for a table row.

  • Foreign Key: Column that refers to a primary key in another table.

Example:

StudentID (Primary Key) → Student table  
CourseID (Foreign Key) → Enroll table  

30. What is TCP and UDP?

Answer:

  • TCP (Transmission Control Protocol): Connection-oriented, reliable, ordered delivery

  • UDP (User Datagram Protocol): Connectionless, faster, no guarantee of delivery

Feature TCP UDP
Reliability Yes No
Speed Slower Faster
Use File transfer, emails Streaming, gaming

31. Explain OSI vs TCP/IP Model

Answer:

OSI TCP/IP
7 layers 4 layers
Theoretical model Practical model
Layered architecture Simplified architecture
Application, Presentation, Session, Transport, Network, Data Link, Physical Application, Transport, Internet, Network Access

32. Difference between Stack and Heap Memory

Feature Stack Heap
Allocation LIFO Dynamic
Lifetime Temporary Until manually freed
Size Smaller Larger
Use Function calls Dynamic objects

33. What is Polymorphism in OOP?

Answer:
Polymorphism allows objects of different types to be treated as objects of a common base type.

Types:

  • Compile-time (Static): Method overloading, operator overloading

  • Run-time (Dynamic): Method overriding

Example:

class Shape {
    void draw() { System.out.println("Drawing shape"); }
}
class Circle extends Shape {
    void draw() { System.out.println("Drawing circle"); }
}

34. Difference between Overloading and Overriding

Feature Overloading Overriding
Compile/Run Compile-time Run-time
Method name Same Same
Parameters Different Same
Return type Can be different Must be same or covariant

35. What is Recursion vs Iteration?

Feature Recursion Iteration
Definition Function calls itself Looping (for, while)
Memory Uses stack Less memory
Example Factorial using recursion Factorial using loop

36. What is a Graph?

Answer:
A graph is a data structure consisting of vertices (nodes) and edges (connections).

Types:

  • Directed / Undirected

  • Weighted / Unweighted

  • Cyclic / Acyclic

Example:

  • Social network → users as nodes, friendships as edges


37. What is the difference between BFS and DFS?

Feature BFS (Breadth First Search) DFS (Depth First Search)
Approach Level-wise Depth-wise
Data Structure Queue Stack/Recursion
Use Shortest path Pathfinding, solving puzzles

38. Difference between Static and Dynamic Binding

Feature Static Binding Dynamic Binding
Time Compile-time Run-time
Method Private, final Overridden methods
Example Method overloading Method overriding

39. What is Exception Handling?

Answer:
Exception handling manages runtime errors to prevent program crashes.

Common keywords (Java/C#):

  • try – Code that may throw exception

  • catch – Handles exception

  • finally – Code executed regardless of exception

  • throw – Throws exception manually

Example (Java):

try {
    int result = 10 / 0;
} catch(ArithmeticException e) {
    System.out.println("Cannot divide by zero");
}

40. Difference between Array and Linked List

Feature Array Linked List
Memory Contiguous Non-contiguous
Size Fixed Dynamic
Access O(1) O(n)
Insertion/Deletion Costly Efficient

41. What is a Queue and its types?

Answer:
A queue is a linear data structure that follows FIFO (First In First Out) principle.
Types of Queue:

  1. Simple Queue – Linear queue, standard FIFO.

  2. Circular Queue – Last position connects back to the first.

  3. Priority Queue – Elements are processed based on priority.

  4. Deque (Double-Ended Queue) – Insert/delete from both ends.

Example in Python:

from collections import deque
q = deque([1,2,3])
q.append(4)   # enqueue
q.popleft()   # dequeue

42. Difference between Linear and Non-linear Data Structures

Feature Linear Non-linear
Data arrangement Sequential Hierarchical/Graph
Examples Array, Linked List, Stack, Queue Tree, Graph
Traversal Simple Complex

43. What is a Heap Data Structure?

Answer:
Heap is a complete binary tree used for priority-based operations.

  • Max Heap – Parent ≥ Children

  • Min Heap – Parent ≤ Children

Use: Priority queues, Heap sort, Memory management.


44. What is Binary Search and its complexity?

Answer:
Binary search finds an element in a sorted array by repeatedly dividing the search interval in half.

Algorithm:

  1. Find middle element.

  2. If key = middle, return index.

  3. If key < middle, search left half.

  4. Else, search right half.

Complexity: O(log n)


45. Difference between Linear Search and Binary Search

Feature Linear Search Binary Search
Array must be sorted No Yes
Complexity O(n) O(log n)
Approach Sequential Divide and Conquer
Use Small datasets Large datasets

46. What is a Graph Traversal?

Answer:
Graph traversal is visiting all nodes of a graph in a systematic way.

Methods:

  • BFS (Breadth First Search) – Level order using queue

  • DFS (Depth First Search) – Depthwise using recursion/stack

Applications: Pathfinding, network analysis.


47. What is Virtualization in Cloud Computing?

Answer:
Virtualization allows multiple virtual machines (VMs) to run on a single physical machine using a hypervisor.

Benefits:

  • Resource optimization

  • Isolation

  • Easier backup & migration

Example: VMware, Hyper-V


48. What is SQL Injection?

Answer:
SQL Injection is a security vulnerability where attackers manipulate SQL queries to access unauthorized data.

Example:

SELECT * FROM users WHERE username = 'admin' OR 1=1;

Prevention: Use prepared statements, parameterized queries.


49. What is Indexing in DBMS?

Answer:
Indexing is a technique to improve database query performance by creating a data structure that allows fast search.

Types:

  • Primary Index – On primary key

  • Secondary Index – On non-primary columns

  • Clustered Index – Data physically ordered


50. Difference between SQL and NoSQL

Feature SQL NoSQL
Structure Tables (Relational) Documents, Key-Value, Graph
Schema Fixed Flexible
Transactions ACID BASE
Example MySQL, Oracle MongoDB, Cassandra

51. What is a Deadlock and Starvation?

Answer:

  • Deadlock: Two or more processes wait indefinitely for resources held by each other.

  • Starvation: A process waits indefinitely because higher-priority processes keep executing.

Difference: Deadlock stops all processes; starvation affects only some processes.


52. Explain Semaphore in OS

Answer:
Semaphore is a synchronization tool used to control access to shared resources in concurrent systems.

Types:

  • Binary Semaphore: 0 or 1 (Mutex)

  • Counting Semaphore: Integer value representing available resources

Example:

wait(semaphore);
critical_section();
signal(semaphore);

53. What is the difference between Process and Thread?

Feature Process Thread
Definition Program in execution Lightweight process within a process
Memory Separate Shared memory
Creation Heavyweight Lightweight
Context Switch Expensive Cheap

54. What is Cloud Deployment Models?

Answer:

  1. Public Cloud: Services available to general public (AWS, Azure).

  2. Private Cloud: Exclusive to a company.

  3. Hybrid Cloud: Combination of Public & Private Cloud.

  4. Community Cloud: Shared by multiple organizations.


55. Difference between GET and POST in HTTP

Feature GET POST
Data URL appended Request body
Security Low High
Cache Can be cached Cannot be cached
Idempotent Yes No

56. Explain REST API

Answer:
REST (Representational State Transfer) is an architectural style for web services.

Key Points:

  • Stateless communication

  • CRUD operations mapped to HTTP methods:

    • GET → Read

    • POST → Create

    • PUT → Update

    • DELETE → Delete

  • Uses JSON/XML for data exchange


57. Difference between HTTP and HTTPS

Feature HTTP HTTPS
Security Not secure Secure (SSL/TLS)
Port 80 443
Encryption No Yes

58. What is Machine Learning?

Answer:
Machine Learning is a subset of AI where systems learn patterns from data without explicit programming.

Types:

  • Supervised Learning – Labeled data (Regression, Classification)

  • Unsupervised Learning – Unlabeled data (Clustering, Association)

  • Reinforcement Learning – Learning via rewards/punishments


59. Difference between AI, ML, and DL

Feature AI ML DL
Definition Intelligence simulation Learn from data Learn using neural networks
Complexity Simple Moderate High
Example Chess AI Predict stock prices Image recognition

60. What is an IDE?

Answer:
IDE (Integrated Development Environment) is a software application that provides:

  • Code editor

  • Compiler/Interpreter

  • Debugger

  • Build automation

Example: Eclipse, Visual Studio, PyCharm

Experienced Interview Questions

 

1. Explain the difference between Stack and Heap memory.

Answer:

Feature Stack Heap
Memory Allocation Static Dynamic
Lifetime Function execution time Until manually freed or GC
Access Fast Slower
Size Limited Large
Use Case Local variables, function calls Dynamic objects
Example int x = 10; inside a function new Object() in Java

2. What is a Deadlock? How can it be prevented?

Answer:
Deadlock occurs when two or more processes wait indefinitely for resources held by each other.

Necessary Conditions:

  1. Mutual exclusion

  2. Hold and wait

  3. No preemption

  4. Circular wait

Prevention Techniques:

  • Deadlock Prevention: Ensure one of the above conditions never holds.

  • Deadlock Avoidance: Use algorithms like Banker’s algorithm to allocate resources safely.

  • Deadlock Detection: Detect and terminate/restart processes when deadlock occurs.


3. Explain Virtual Memory and Paging.

Answer:
Virtual memory allows the system to run programs larger than physical RAM using a portion of the hard disk.

Paging: Memory is divided into fixed-size pages (logical memory) and frames (physical memory). Pages are mapped to frames using a page table.

Advantages:

  • Efficient memory utilization

  • Supports multitasking

  • Eliminates external fragmentation


4. What is Normalization in DBMS? Why is it important?

Answer:
Normalization is a process of organizing database tables to reduce redundancy and improve data integrity.

Normal Forms:

  1. 1NF: No repeating groups

  2. 2NF: No partial dependency

  3. 3NF: No transitive dependency

  4. BCNF: Stronger version of 3NF

Example:
Before 1NF:

Student Courses
John Math, Physics

After 1NF:

Student Course
John Math
John Physics

5. Difference between TCP and UDP

Feature TCP UDP
Connection Connection-oriented Connectionless
Reliability Reliable Unreliable
Flow Control Yes No
Use Case File transfer, emails Video streaming, gaming

6. Explain OSI and TCP/IP Models

Answer:

OSI Model (7 Layers):

  1. Physical – Bits transmission

  2. Data Link – MAC addressing, error detection

  3. Network – IP addressing, routing

  4. Transport – TCP/UDP

  5. Session – Session management

  6. Presentation – Encryption/Translation

  7. Application – HTTP, FTP

TCP/IP Model (4 Layers):

  1. Network Interface – Physical + Data Link

  2. Internet – IP addressing

  3. Transport – TCP/UDP

  4. Application – HTTP, FTP, DNS

Key Difference: OSI is theoretical; TCP/IP is practical.


7. What is Polymorphism in OOP?

Answer:
Polymorphism allows objects to take multiple forms.

Types:

  • Compile-time (Static): Method overloading, operator overloading

  • Run-time (Dynamic): Method overriding

Example (Java):

class Shape {
    void draw() { System.out.println("Drawing shape"); }
}
class Circle extends Shape {
    void draw() { System.out.println("Drawing circle"); }
}

At runtime, Shape s = new Circle(); s.draw(); will call Circle’s method.


8. Difference between Overloading and Overriding

Feature Overloading Overriding
Compile/Run Compile-time Run-time
Parameters Different Same
Return Type Can differ Must be same/covariant
Example int sum(int a, int b) & float sum(float a, float b) Child class overrides parent method

9. Explain REST vs SOAP APIs

Answer:

Feature REST SOAP
Protocol HTTP XML-based protocol
Data Format JSON, XML XML
State Stateless Can be Stateful
Complexity Simple Complex
Use Modern web apps Enterprise apps

10. What is Machine Learning? Types?

Answer:
Machine Learning (ML) is a subset of AI where systems learn patterns from data without explicit programming.

Types:

  1. Supervised Learning: Labeled data → Regression, Classification

  2. Unsupervised Learning: Unlabeled data → Clustering, Association

  3. Reinforcement Learning: Learn via rewards/punishments → Games, Robotics


11. Explain Cloud Deployment Models

Answer:

  1. Public Cloud: Shared resources, accessible to all (AWS, Azure)

  2. Private Cloud: Dedicated resources, internal use

  3. Hybrid Cloud: Combination of Public & Private

  4. Community Cloud: Shared by specific organizations


12. Explain the difference between SQL and NoSQL

Feature SQL NoSQL
Structure Relational tables Key-value, Document, Graph
Schema Fixed Flexible
ACID Yes BASE (Eventually consistent)
Example MySQL, Oracle MongoDB, Cassandra

13. What is Indexing in DBMS?

Answer:
Indexing improves query performance by creating a data structure (B-Tree, Hash Table) that allows fast search.

Types:

  • Primary Index – On primary key

  • Secondary Index – On non-primary key

  • Clustered Index – Data physically ordered


14. Explain Binary Search Tree (BST) and its complexity

Answer:
BST is a binary tree where left child < root < right child.

Operations:

  • Search – O(log n) on average, O(n) worst-case (skewed)

  • Insert – O(log n)

  • Delete – O(log n)

Example:

       15
      /  \
     10   20
    / \   / \
   8  12 17 25

15. Difference between Process and Thread

Feature Process Thread
Definition Program in execution Lightweight process inside a process
Memory Separate Shared
Creation Heavy Light
Context Switch Expensive Cheap

16. What is a Graph and its types?

Answer:
A graph is a collection of nodes (vertices) connected by edges.

Types:

  1. Directed / Undirected

  2. Weighted / Unweighted

  3. Cyclic / Acyclic

  4. Special Graphs: Tree, DAG

Applications: Social networks, GPS navigation, recommendation systems


17. Explain BFS vs DFS

Feature BFS DFS
Traversal Level by level Depth first
Data Structure Queue Stack / Recursion
Use Case Shortest path Topological sort, puzzles

18. What is Caching? Types of Caching

Answer:
Caching stores frequently used data in faster storage to improve performance.

Types:

  • Memory Cache – RAM

  • Disk Cache – Hard drive

  • Browser Cache – Web content

  • Database Cache – Query results


19. What is Load Balancing?

Answer:
Load balancing distributes incoming network traffic across multiple servers to ensure high availability and reliability.

Types:

  • Round Robin – Sequential distribution

  • Least Connections – Server with fewest connections

  • IP Hash – Based on client IP


20. Explain Microservices Architecture

Answer:
Microservices architecture divides an application into small, independent services that communicate via APIs.

Advantages:

  • Scalability

  • Independent deployment

  • Fault isolation

Example: E-commerce app → Separate services for payment, inventory, user management


21. What is a Hash Table? Explain Collision Handling Techniques

Answer:
A Hash Table is a data structure that stores key-value pairs and uses a hash function to compute an index for each key.

Collision: When two keys hash to the same index.

Collision Handling Techniques:

  1. Chaining: Store multiple elements at the same index using a linked list.

  2. Open Addressing: Find the next available slot using techniques like Linear Probing, Quadratic Probing, or Double Hashing.

Example:

hash_table = [None]*10
key = 15
index = key % 10  # Hash Function

22. What is a Trie and its Applications?

Answer:
A Trie is a tree-like data structure used to store strings efficiently. Each node represents a character.

Applications:

  • Autocomplete

  • Spell checking

  • IP routing (Longest prefix match)

Example: Words “cat”, “cap”, “can” share the prefix “ca”.


23. Explain LRU and LFU Cache

Answer:
Caching policies used to decide which items to evict when the cache is full:

  • LRU (Least Recently Used): Removes the item that was used the longest time ago.

  • LFU (Least Frequently Used): Removes the item with the lowest access frequency.

Implementation: HashMap + Doubly Linked List for O(1) access (LRU).


24. Difference between B-Tree and B+ Tree

Feature B-Tree B+ Tree
Data Storage Internal & Leaf nodes Leaf nodes only
Traversal All nodes Leaf nodes (linked list for range queries)
Use Case Indexed DB search File systems, database indexing
Complexity O(log n) O(log n)

25. Explain Red-Black Tree and its Properties

Answer:
A Red-Black Tree is a self-balancing binary search tree with the following properties:

  1. Each node is red or black.

  2. Root is always black.

  3. Red nodes cannot have red children (no two reds in a row).

  4. Every path from a node to its leaf has the same number of black nodes.

Use Case: Balanced search tree for efficient insertion/deletion.


26. Explain Merge Sort vs Quick Sort

Feature Merge Sort Quick Sort
Approach Divide and Conquer Divide and Conquer
Worst-case O(n log n) O(n²)
Best-case O(n log n) O(n log n)
Space Complexity O(n) O(log n) (in-place)
Stability Yes No

27. Explain Dynamic Programming

Answer:
Dynamic Programming (DP) is a technique to solve problems by breaking them into subproblems and storing results to avoid recomputation.

Example: Fibonacci sequence

def fib(n):
    dp = [0]*(n+1)
    dp[0], dp[1] = 0, 1
    for i in range(2, n+1):
        dp[i] = dp[i-1] + dp[i-2]
    return dp[n]

Applications:

  • Knapsack problem

  • Longest Common Subsequence

  • Matrix Chain Multiplication


28. Explain ACID Properties in DBMS

Answer:
ACID ensures reliable transaction processing:

  • Atomicity: All or nothing

  • Consistency: DB remains in valid state

  • Isolation: Transactions don’t interfere

  • Durability: Committed changes persist

Example: Banking transfer ensures debit and credit are atomic.


29. What is CAP Theorem?

Answer:
CAP Theorem states that a distributed system can have only two out of three guarantees at the same time:

  • Consistency: Every read receives the latest write

  • Availability: Every request gets a response

  • Partition Tolerance: System works despite network partitions

Example: NoSQL systems like MongoDB, Cassandra follow CAP trade-offs.


30. Difference between Synchronous and Asynchronous Communication

Feature Synchronous Asynchronous
Execution Waits for response Does not wait
Use Case RPC, Function Calls Message Queues, Event-driven systems
Efficiency Can be slower More efficient

31. What is Event-Driven Architecture?

Answer:
In Event-Driven Architecture, components communicate via events instead of direct calls.

Advantages:

  • Decoupled components

  • Scalable systems

  • Real-time processing

Example: Kafka, RabbitMQ for messaging.


32. Difference between REST and GraphQL

Feature REST GraphQL
Data Fetch Fixed endpoints Flexible queries
Over-fetching Possible Avoided
Versioning Required Not required
Example /users/1 { user(id:1) {name, email} }

33. Explain OAuth 2.0

Answer:
OAuth 2.0 is an authorization framework that allows third-party apps to access user resources without sharing credentials.

Roles:

  • Resource Owner – User

  • Client – Application requesting access

  • Authorization Server – Issues tokens

  • Resource Server – Hosts resources

Example: Login with Google/Facebook.


34. What is Docker and its benefits?

Answer:
Docker is a containerization platform to run applications in lightweight isolated environments.

Benefits:

  • Portability

  • Consistency across environments

  • Efficient resource utilization

Commands:

  • docker build – Build image

  • docker run – Run container

  • docker ps – List running containers


35. Explain Kubernetes (K8s)

Answer:
Kubernetes is a container orchestration platform to manage deployment, scaling, and management of containerized applications.

Components:

  • Pod – Smallest deployable unit

  • Node – Worker machine

  • Cluster – Master + Nodes

  • Service – Networking abstraction

Use Case: Scalable microservices deployment.


36. What is OAuth vs JWT?

Answer:

Feature OAuth JWT
Purpose Authorization framework Token format
State Server maintains state Stateless
Example Login with Google Access tokens in APIs

37. Explain RabbitMQ vs Kafka

Feature RabbitMQ Kafka
Type Message Broker Distributed Streaming
Message Model Queue-based Log-based
Persistence Optional Durable by default
Use Case Real-time messaging High-throughput event streaming

38. What is CAPACITY planning in Cloud?

Answer:
Capacity planning is predicting resource requirements to ensure applications scale efficiently without overprovisioning.

Steps:

  • Measure current usage

  • Forecast growth

  • Allocate resources dynamically (autoscaling in AWS/Azure)


39. Explain CI/CD

Answer:

  • CI (Continuous Integration): Developers merge code frequently → Automated builds/tests

  • CD (Continuous Deployment/Delivery): Code changes automatically deployed to production or staging

Tools: Jenkins, GitLab CI/CD, CircleCI


40. Difference between Monolithic and Microservices Architecture

Feature Monolithic Microservices
Structure Single codebase Independent services
Scalability Hard Easy
Deployment Single Independent
Fault Isolation Poor Good

41. What is Sharding in Databases?

Answer:
Sharding is a database partitioning technique that splits a large database into smaller, faster, and more manageable pieces called shards.

Types:

  1. Horizontal Sharding: Rows are distributed across multiple databases.

  2. Vertical Sharding: Columns are split into different tables or databases.

Use Case: High-scale systems like Twitter, Amazon, where one database cannot handle all traffic.


42. What is Consistent Hashing?

Answer:
Consistent hashing is a technique to distribute keys across nodes in a way that minimizes re-distribution when nodes are added/removed.

Use Case: Distributed caching systems like Redis Cluster, Memcached.

Example: If a node is removed, only the keys in that node need redistribution, not the entire hash table.


43. Difference between Horizontal and Vertical Scaling

Feature Horizontal Scaling Vertical Scaling
Method Add more machines Increase resources of a single machine
Cost Moderate to high High upfront
Fault Tolerance High Low
Example Load-balanced web servers Upgrading RAM/CPU

44. Explain CAP Theorem with Examples

Answer:
CAP Theorem: Distributed systems can guarantee only 2 out of 3:

  1. Consistency: All nodes see the same data at the same time.

  2. Availability: Every request receives a response.

  3. Partition Tolerance: System continues to work despite network failure.

Example:

  • MongoDB: AP (Availability + Partition-tolerant)

  • HBase: CP (Consistency + Partition-tolerant)


45. What is CQRS (Command Query Responsibility Segregation)?

Answer:
CQRS is an architecture pattern that separates read operations from write operations.

Advantages:

  • Optimized reads and writes separately

  • Supports event sourcing

  • Easier scaling

Use Case: High-traffic e-commerce platforms where reads are frequent.


46. Difference between Strong and Eventual Consistency

Feature Strong Consistency Eventual Consistency
Guarantee Immediate consistency across nodes Data may take time to propagate
Latency Higher Lower
Use Case Banking systems Social media feeds

47. Explain CAP vs ACID vs BASE

  • ACID (DB transactions): Atomicity, Consistency, Isolation, Durability – used in SQL databases.

  • BASE (NoSQL): Basically Available, Soft state, Eventually consistent – used in NoSQL systems.

  • CAP (Distributed systems): Consistency, Availability, Partition tolerance – trade-offs for distributed DBs.

Example: SQL DB → ACID; MongoDB → BASE; Cassandra → AP (CAP).


48. What is Rate Limiting in APIs?

Answer:
Rate limiting restricts the number of requests a client can make in a given time to prevent abuse or overload.

Techniques:

  1. Fixed Window Counter

  2. Sliding Window Log

  3. Token Bucket / Leaky Bucket

Use Case: Preventing API abuse like login attempts or public API usage.


49. Explain OAuth vs JWT in API Security

Feature OAuth JWT
Purpose Authorization Token format for authentication
State Server maintains Stateless
Use Login via third-party API token exchange
Example Google/Facebook login Access token in REST API

50. Difference between Synchronous and Asynchronous Systems

Feature Synchronous Asynchronous
Communication Waits for response Does not wait
Throughput Low High
Use Case RPC calls Event-driven architectures
Example HTTP request-response Kafka, RabbitMQ messaging

51. Explain Event-Driven Architecture (EDA)

Answer:
EDA decouples components using events instead of direct calls.

Advantages:

  • Loose coupling

  • Real-time updates

  • Scalability

Example: E-commerce: OrderPlaced event triggers Payment and Inventory services asynchronously.


52. Explain Load Balancing Techniques

Technique Description
Round Robin Requests distributed sequentially
Least Connections Request sent to server with fewest active connections
IP Hash Client IP determines server
Weighted Load Balancing Servers assigned weights based on capacity

Use Case: Web servers, cloud microservices.


53. Difference between Monolithic vs Microservices Architecture

Feature Monolithic Microservices
Codebase Single large codebase Multiple independent services
Deployment Single deployment Independent deployments
Scalability Limited High
Fault Isolation Poor Good
Example Legacy ERP Amazon, Netflix

54. Explain Docker and Containers

Answer:
Docker enables containerization, packaging apps with dependencies to run consistently across environments.

Benefits:

  • Portability

  • Isolation

  • Resource efficiency

Commands:

  • docker build → Build image

  • docker run → Run container

  • docker ps → List containers


55. Explain Kubernetes (K8s)

Answer:
Kubernetes orchestrates containerized applications across clusters.

Key Concepts:

  • Pod: Smallest deployable unit

  • Node: Worker machine

  • Cluster: Master + multiple nodes

  • Service: Networking abstraction

Use Case: Auto-scaling microservices in production.


56. Difference between CI/CD and DevOps

Feature CI/CD DevOps
Focus Automation of builds/tests/deployment Culture + processes + tools
Scope Part of DevOps pipeline End-to-end software lifecycle
Example Jenkins pipeline CI/CD + Monitoring + Infrastructure as Code

57. Explain System Design: Caching Strategies

Answer:
Caching improves system performance by storing frequently accessed data.

Strategies:

  • Write-through: Update cache + DB simultaneously

  • Write-back: Update cache only, write to DB later

  • Read-through: Cache auto-fetches from DB if missing

  • Cache eviction: LRU, LFU

Tools: Redis, Memcached


58. Explain Sharding + Replication in Databases

  • Sharding: Splits DB into smaller shards for scalability

  • Replication: Copies of DB for redundancy and fault tolerance

  • Use Case: High-traffic apps like Twitter, eBay


59. Explain CAP vs ACID vs BASE with Examples

Concept Use Example
ACID SQL DB transactions MySQL, Oracle
BASE Eventual consistency MongoDB, Cassandra
CAP Distributed systems trade-offs Cassandra (AP), HBase (CP)

60. Explain Consistent Hashing with Example

  • Used to distribute load among nodes

  • Minimizes rehashing when nodes are added/removed

  • Example: Distributed cache (Redis Cluster)

  • Reduces downtime during scaling