0% found this document useful (0 votes)
2 views27 pages

Programming Problem Solving

Uploaded by

01saifulislam0
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views27 pages

Programming Problem Solving

Uploaded by

01saifulislam0
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Q1. What is problem solving in programming?

Discuss the major steps involved in solving


a computational problem systematically.
Programming Problem Solving is the process of understanding a problem, finding a solution,
writing code, testing it, and improving it when needed. It helps programmers solve different
types of real-life and software-related problems using logical thinking and programming skills.

Major Steps of Problem Solving:


1. Understand the problem – identify the input and output.
2. Analyze the problem – understand the requirements and conditions.
3. Design an algorithm – make a step-by-step plan to solve it.
4. Write the code – convert the algorithm into a program.
5. Test and debug – find and fix errors.
6. Improve the solution – make the program faster and use less memory.
Following these steps helps programmers write correct and efficient programs.

Q2. Differentiate between compile-time errors, run-time errors, and logical errors with
suitable examples.
When It Program Difficulty to
Error Type Example Detection
Occurs Execution Fix
Missing
Compile- Before the semicolon, Found by the Program Usually easy
time Error program runs undeclared compiler cannot run to fix
variable
While the
Run-time Division by zero, Found during Program may
program is Moderate
Error invalid array index execution stop or crash
running
Program runs Often
Logical Using + instead of Found by Program runs
but gives wrong hardest to
Error * testing normally
result find
Compile-time errors stop the program from running. Run-time errors occur during execution
and may crash the program. Logical errors do not stop the program but produce incorrect
results.

Q3. Explain the importance of debugging and profiling in software development. Briefly
discuss commonly used debugging strategies.
Debugging is the process of finding, analyzing, and fixing errors (bugs) in a program. It helps
programmers identify problems, improve program performance, and ensure that the software
works correctly and produces the expected results.
Profiling is the process of checking a program's performance to find which parts use the most
time or memory. It helps programmers improve the speed and efficiency of a program.
Common Debugging Strategies:
1. Print Debugging — print variable values to check program behavior.
2. Using a Debugger — use tools to find and examine errors.
3. Rubber Duck Debugging — explain the code step by step to find mistakes.
4. Divide and Conquer — check small parts of the code separately.
5. Code Review — ask others to review the code.
6. Unit Testing — test each function individually to find problems.
7. Checking Error Messages — read error messages carefully to identify the cause.
8. Log Analysis — examine log files to track program activities and errors.
9. Reproducing the Bug — run the same steps again to understand the problem better.

Q4. What is the Standard Template Library (STL)? Explain its major components.
STL (Standard Template Library) is a built-in library in C++ that provides ready-made data
structures and algorithms. It includes containers such as vector, map, set, stack, and queue,
along with useful functions like sort(), find(), and reverse().
Major Components of STL:
1. Containers – Used to store data. Examples: vector, set, map, stack, and queue.
2. Algorithms – Ready-made functions such as sort(), find(), reverse(), and count().
3. Iterators – Used to access and move through elements in a container.
4. Function Objects (Functors) – Special objects that work like functions and help
customize operations.
5. Allocators – Manage memory allocation and deallocation for STL containers.
6. Adapters – Modify or simplify the use of containers and functions. Examples: stack,
queue, and priority_queue.
STL makes code shorter, easier to understand, faster, and more efficient. It is widely used in
competitive programming and software development.

Q5. Compare vector, list, and map containers with suitable applications.
Vector
1. Stores data in a dynamic array.
2. Elements can be accessed quickly using an index.
3. Easy to add elements at the end.
4. Good for storing lists of numbers or items.
5. Example: vector<int> v;
List
1. Stores data as linked nodes.
2. Easy to add or remove elements in the middle.
3. Accessing elements is slower than a vector.
4. Useful when data changes frequently.
5. Example: list<int> l;
Map
1. Stores data as key-value pairs.
2. Each key is unique.
3. Easy to search data using a key.
4. Useful for storing names with values or frequencies.
5. Example: map<string, int> m;
Applications:
• vector is used when we need to find data quickly.
• vector is useful for storing a list of numbers or items.
• list is used when we often add or remove data.
• list is good when data changes many times.
• map is used when we want to find data using a key.
• map is useful for counting items and storing simple records.
These containers are widely used in C++ programs because they make data storage and
management easier.

Q6. Discuss the advantages of using STL algorithms over manually written algorithms.
Advantages of Using STL Algorithms Over Manually Written Algorithms
STL algorithms are ready-made functions available in the C++ Standard Library. They help
programmers write code more quickly and easily.
Advantages:
1. Save time because there is no need to write common algorithms from scratch.
2. Use less code and make programs shorter.
3. Well-tested and more reliable.
4. Usually faster and more efficient.
5. Work with different STL containers through iterators.
6. Improve code readability and maintenance.
7. Reduce the chance of programming mistakes.
8. Easy to learn and use.
9. Useful in competitive programming where speed is important.
Examples of STL algorithms are sort(), find(), count(), and binary_search(). They make
programming faster, simpler, and more efficient.

Q7. Explain the importance of Number Theory in competitive programming.


Importance of Number Theory in Competitive Programming
Number Theory is a branch of mathematics that deals with numbers and their properties. It is
very important in competitive programming because many contest problems are based on
mathematical calculations.
Important topics include prime numbers, GCD, LCM, divisors, factorization, and modular
arithmetic. These topics help programmers solve problems quickly and efficiently.
Importance:
1. Helps solve mathematical problems faster.
2. Useful for prime number and divisor problems.
3. Helps handle very large numbers using modular arithmetic.
4. Used in GCD and LCM calculations.
5. Important for counting and combinatorial problems.
6. Commonly used in cryptography and security-related problems.
7. Improves problem-solving skills in programming contests.
A good understanding of Number Theory helps programmers write faster and more efficient
solutions.

Q8. Describe the Sieve of Eratosthenes algorithm for generating prime numbers.
The Sieve of Eratosthenes is a simple and fast method used to find all prime numbers from 2
to N by removing numbers that are multiples of other numbers.
Steps:
1. Create a list of numbers from 2 to N.
2. Start with 2, the first prime number.
3. Mark all multiples of 2 as not prime.
4. Move to the next unmarked number (3) and mark its multiples.
5. Continue this process until all necessary numbers are checked.
6. The remaining unmarked numbers are prime numbers.
Example (N = 20):
 Mark multiples of 2 → 4, 6, 8, 10, 12, 14, 16, 18, 20

 Mark multiples of 3 → 9, 15

Prime Numbers: 2, 3, 5, 7, 11, 13, 17, 19


This method is widely used in competitive programming for prime number problems.
Q9. Write an algorithm or pseudocode to calculate the Greatest Common Divisor (GCD)
using the Euclidean Algorithm.
The Euclidean Algorithm is a simple method for finding the Greatest Common Divisor (GCD)
of two numbers. It repeatedly divides the numbers until the remainder becomes 0.
Pseudocode:
Start
Input a, b
While b ≠ 0
r = a mod b
a=b
b=r
End While
Print a
Stop

Algorithm:
1. Input two numbers a and b.
2. Check whether b = 0.
3. If b = 0, return a as the GCD and stop.
4. Otherwise, calculate the remainder r = a mod b.
5. Replace a with b and b with r.
6. Repeat Steps 2–5 until b = 0.
7. The final value of a is the GCD.
Example:
GCD(56, 98) → GCD(98, 56) → GCD(56, 42) → GCD(42, 14) → GCD(14, 0)
Answer: 14.

Q10. What are lambda expressions in C++? Explain their advantages with examples.
A lambda expression is a small unnamed function introduced in C++11. It can be written
directly inside the code without creating a separate function. Lambda expressions make
programs shorter, cleaner, and easier to understand.
Syntax:
[capture](parameters) {
// code
};
Example:
auto square = [](int x) {
return x * x;
};

cout << square(5);


Output: 25
Lambda expressions are commonly used with STL functions such as sort(), for_each(), and
other algorithms. They help programmers write simple and efficient code.
Advantages:
1. Reduces code size.
2. No need to create a separate function.
3. Works well with STL algorithms.
4. Makes code easier to read.
5. Useful for short and simple tasks.
6. Can use values from outside the lambda using capture lists.
7. Saves time during competitive programming.
Lambda expressions are widely used in modern C++ programming.

Q11. What are smart pointers? Explain different types of smart pointers available in
modern C++.
Smart pointers are special C++ pointers that automatically manage memory. They free memory
when it is no longer needed, helping to prevent memory leaks and making programs safer and
easier to manage.
Types of Smart Pointers:
1. unique_ptr – Has only one owner. It cannot be copied to another pointer. When it goes
out of scope, the memory is automatically released.
2. shared_ptr – Allows multiple pointers to share the same object. Memory is released
when the last shared_ptr is destroyed.
3. weak_ptr – Does not own the object. It is used with shared_ptr and helps avoid circular
references.
Smart pointers make memory management safer, easier, and more reliable than using normal
pointers.

Q12. How do smart pointers help prevent memory leakage in software systems?
How Smart Pointers Help Prevent Memory Leakage
A memory leak happens when a program uses memory but does not release it after use. This
can waste memory and make the program slow or unstable.
Smart pointers help prevent memory leaks by automatically releasing memory when it is no
longer needed. Programmers do not need to use delete manually. For example, a unique_ptr
automatically frees memory when it goes out of scope. A shared_ptr keeps track of how many
pointers are using the same object and frees the memory when it is no longer used.
This makes memory management safer, easier, and more reliable.

Q13. Define graph data structure. Differentiate between directed and undirected graphs.
Define Graph Data Structure
A graph is a non-linear data structure that consists of a set of vertices (nodes) and edges that
connect them. It is used to represent relationships between different objects. Graphs can be
directed or undirected, depending on whether the connections have a direction. They are widely
used in computer networks, social networks, maps, and many other applications.
Feature Directed Graph Undirected Graph
Direction Edges have a direction Edges have no direction
Connection One-way connection Two-way connection
Notation u→v u—v
Degree Has in-degree and out-degree Has only degree
Example Web pages, task scheduling Social networks, road maps
Movement Can move in one direction only Can move in both directions
A directed graph has edges with a specific direction, while an undirected graph has edges
that can be traveled in both directions.

Q14. Explain Breadth First Search (BFS) and Depth First Search (DFS) algorithms.
Breadth First Search (BFS)
BFS is a method used to visit all nodes of a graph step by step. It starts from a node and first
visits all nearby nodes, then moves to the next level. BFS uses a queue. It is often used to find
the shortest path in a graph.
Depth First Search (DFS)
DFS is a method used to visit graph nodes by following one path as far as possible. When it
cannot go further, it returns and checks another path. DFS uses a stack or recursion. It is useful
for exploring all parts of a graph.
Difference: BFS visits nodes level by level, while DFS follows one path deeply before moving
to another path.
Q15. Discuss the applications of graph traversal algorithms in real-world problem solving.
Applications of Graph Traversal Algorithms in Real Life
Graph traversal algorithms such as BFS and DFS are used in many real-world applications.
BFS Applications:
1. Finding the shortest path in maps and GPS systems.
2. Finding friends or connections in social networks.
3. Sending data through computer networks.
4. Exploring web pages by search engines.
DFS Applications:
1. Finding cycles in a graph or network.
2. Solving mazes and path-finding problems.
3. Task scheduling and ordering tasks.
4. Finding connected groups in a network.
5. Exploring all possible paths in a graph.
These algorithms are widely used in computer networks, web applications, transportation
systems, and many other software systems.

Q16. What is time complexity? Explain Big-O notation with example in brief.
What is Time Complexity?
Time complexity is a way to measure how much time an algorithm takes as the input size
increases. It helps programmers compare algorithms and choose the faster one.
Big-O Notation
Big-O notation is used to show the running time of an algorithm in the worst case.
Common Big-O Values:
 O(1) – Constant time (e.g., accessing an array element).

 O(log n) – Logarithmic time (e.g., binary search).

 O(n) – Linear time (e.g., linear search).

 O(n log n) – Used in efficient sorting algorithms like merge sort.

 O(n²) – Quadratic time (e.g., bubble sort).

Example:
If you search for a number in an unsorted array of 1000 elements, you may need to check all
1000 elements. This is O(n) time complexity.
Time complexity helps programmers write faster and more efficient programs.

Q17. Differentiate between iterative and recursive approaches to problem solving.


Feature Iterative Approach Recursive Approach
Definition Uses loops such as for and while A function calls itself
Repetition Repeats steps using loops Repeats steps using function calls
Memory Use Uses less memory Uses more memory
Speed Usually faster Usually slower
Code Length May be longer Often shorter and simpler
Example Factorial using a for loop Factorial using a recursive function
Summary:
Both methods can solve the same problem. Recursion is easier for some problems like trees and
graphs, while iteration is often preferred when memory and speed are important.

Q18. Discuss different optimization techniques used to reduce execution time and memory
usage in competitive programming.
Optimization Techniques in Competitive Programming
Optimization is important in competitive programming because it helps programs run faster and
use less memory.
Common Optimization Techniques:
1. Use Fast Input/Output – Read and print data quickly.
2. Choose the Right Data Structure – Use efficient structures such as vector, queue, or
unordered_map.
3. Avoid Unnecessary Loops – Reduce extra calculations and repeated work.
4. Use Dynamic Programming (DP) – Store previous results to avoid solving the same
problem again.
5. Use Bit Operations – Some operations can be done faster using bits.
6. Precompute Values – Calculate useful values before processing queries.
7. Use References – Avoid copying large amounts of data.
8. Use Efficient Algorithms – Prefer faster algorithms with lower time complexity.
These techniques help reduce execution time and memory usage, making programs more
efficient.

Q19. Compare linear search and binary search algorithms.


Feature Linear Search Binary Search
Works On Sorted or unsorted data Only sorted data
Checks the middle element and divides the
Method Checks elements one by one
data
Feature Linear Search Binary Search
Time Complexity O(n) O(log n)
Speed Slower for large data Faster for large data
Data
No sorting needed Data must be sorted
Requirement
Easy to understand and
Implementation Slightly more complex
write
Best Use Small lists or unsorted data Large sorted data
Example Search 7 in [3, 7, 1, 9] Search 7 in [1, 3, 5, 7, 9]
Example:
 Linear Search checks 3, then 7 → Found.

 Binary Search checks 5, then 7 → Found.

Summary:
Linear search is simple and works on any list. Binary search is much faster but requires the data
to be sorted first. For large amounts of data, binary search is usually the better choice.

Q20. Explain Merge Sort and Quick Sort algorithms with suitable examples.
Merge Sort Algorithm
1. Divide the array into two equal halves.
2. Recursively sort the left half.
3. Recursively sort the right half.
4. Merge the two sorted halves into one sorted array.
Example:
[5, 3, 1, 4]
→ [5, 3] and [1, 4]
→ [3, 5] and [1, 4]
→ [1, 3, 4, 5]
Time Complexity: O(n log n)

Quick Sort Algorithm


1. Select a pivot element.
2. Place smaller elements on the left of the pivot.
3. Place larger elements on the right of the pivot.
4. Apply the same process to the left and right parts.
5. Continue until the array becomes sorted.
Example:
[3, 6, 1, 4, 2]
Pivot = 4
→ [3, 1, 2] [4] [6]
→ [1, 2, 3, 4, 6]
Time Complexity: Average O(n log n)

Difference:
 Merge Sort divides the array into halves and then merges them.

 Quick Sort uses a pivot to divide the array.

 Merge Sort uses more memory.

 Quick Sort is usually faster in practice.

Q21. Discuss the importance of algorithm analysis in selecting appropriate searching and
sorting techniques.
Importance of Algorithm Analysis in Searching and Sorting
Algorithm analysis helps programmers understand how fast an algorithm works and how much
memory it uses. It helps in choosing the best searching and sorting method for a problem.
For example, Bubble Sort is slow for large data, while Merge Sort can sort large data much
faster. Similarly, Binary Search is much faster than Linear Search when the data is sorted.
Algorithm analysis helps reduce execution time, save memory, and improve program
performance. In competitive programming, it is important because problems have time and
memory limits. Choosing the right algorithm increases the chance of getting the correct answer
quickly.

Q22. What is exception handling? Explain its importance in software development.


Exception Handling
Exception handling is a method used to detect and handle errors that occur while a program is
running. It helps the program deal with unexpected problems without stopping suddenly.
Importance in Software Development:
1. Prevents the program from crashing suddenly.
2. Allows the program to continue running after an error.
3. Makes code easier to manage and understand.
4. Helps programmers find and fix errors more easily.
5. Shows meaningful error messages to users.
6. Improves software reliability and stability.
7. Helps protect important data and resources.
In C++, exception handling is done using try, catch, and throw keywords.

Q23. Discuss the use of try, catch, and throw statements in C++ with suitable examples.
Use of try, catch, and throw in C++
C++ uses try, catch, and throw for exception handling.
 try: Contains the code that may cause an error.

 throw: Used to generate an exception when an error occurs.

 catch: Receives and handles the exception.

Example:
try {
int a = 10, b = 0;

if (b == 0)
throw "Division by zero!";

cout << a / b;
}
catch (const char* msg) {
cout << msg;
}
Output:
Division by zero!
In this example, the throw statement sends an error message, and the catch block handles it.
This prevents the program from crashing and allows it to show a proper error message.
Exception handling is commonly used for file handling, user input, and other operations where
errors may occur.

Q24. Explain how robust coding practices improve software quality and maintainability.
How Robust Coding Practices Improve Software Quality and Maintainability
Robust coding practices help make software reliable, easy to understand, and easy to maintain.
They reduce errors and improve program quality.
Common Robust Coding Practices:
1. Use clear and meaningful variable and function names.
2. Write comments to explain important parts of the code.
3. Divide large programs into small functions.
4. Handle errors properly using exception handling.
5. Check user input before processing it.
6. Test the program regularly to find bugs.
7. Follow a consistent coding style and formatting.
8. Review code to find mistakes and improvements.
These practices make programs easier to read, debug, update, and maintain. They also help
developers work together more effectively.

Q25. What is dynamic programming? Explain its advantages in problem solving.


What is Dynamic Programming (DP)?
Dynamic Programming (DP) is a problem-solving technique used to solve complex problems
by breaking them into smaller problems. The result of each small problem is stored so it can be
used again without solving it repeatedly.
Advantages of Dynamic Programming:
1. Reduces execution time by avoiding repeated calculations.
2. Makes programs faster and more efficient.
3. Saves effort by reusing previously calculated results.
4. Helps solve complex problems more easily.
5. Useful for many programming problems such as Fibonacci, Knapsack, and Shortest Path.
6. Improves overall program performance.
Dynamic Programming is widely used in competitive programming and software development
to solve problems efficiently.

Q26. Differentiate between stack and queue data structures with examples.
Feature Stack Queue
Working Rule LIFO (Last In, First Out) FIFO (First In, First Out)
Data Removal Last added item is removed first First added item is removed first
Insertion Push at the top Insert at the rear (back)
Deletion Pop from the top Delete from the front
Example Browser back button, Undo feature Ticket line, Print queue
STL Example stack<int> s; queue<int> q;
Example:
 Stack: If 1, 2, 3 are added, then 3 is removed first.

 Queue: If 1, 2, 3 are added, then 1 is removed first.

Summary:
A stack follows Last In, First Out (LIFO), while a queue follows First In, First Out (FIFO).
Q27. Explain the concept of recursion with suitable examples in C++.
Concept of Recursion in C++
Recursion is a programming technique where a function calls itself again and again until a
stopping condition is reached. It is useful for solving problems that can be divided into smaller
similar problems.
Example: Factorial
int factorial(int n) {
if (n == 0)
return 1;
return n * factorial(n - 1);
}
Example:
factorial(4)
= 4 × factorial(3)
=4×3×2×1
= 24
Advantages of Recursion:
1. Makes code shorter and easier to understand.
2. Useful for tree and graph problems.
3. Helps solve problems step by step.
Recursion is widely used in programming to solve problems that can be divided into smaller
similar problems.

Q28. What is object-oriented programming (OOP)? Explain its main principles.


What is Object-Oriented Programming (OOP)?
Object-Oriented Programming (OOP) is a programming method where programs are built using
objects and classes. It helps organize code, reuse code, and make programs easier to manage.
Main Principles of OOP:
1. Encapsulation – Keeps data and functions together in a class and protects data from
direct access.
2. Abstraction – Shows only important features and hides unnecessary details.
3. Inheritance – Allows one class to use the properties and functions of another class.
4. Polymorphism – The same function can work in different ways depending on the
situation.
Advantages of OOP:
 Makes code reusable.
 Makes programs easier to understand.
 Helps manage large software projects.
 Improves code maintenance and development.

Q29. Discuss the importance of data structures in software development.


Importance of Data Structures in Software Development
Data structures are ways of storing and organizing data in a computer. They help programs
work faster and manage data more efficiently.
Importance of Data Structures:
1. Help store and organize data properly.
2. Make searching, inserting, and deleting data faster.
3. Improve program performance and efficiency.
4. Reduce memory usage and waste.
5. Help solve different types of programming problems.
6. Are used in many applications such as databases, file systems, and networks.
7. Make programs easier to develop and maintain.
8. Help software handle large amounts of data effectively.
Data structures are an important part of programming and software development because they
help build fast, efficient, and reliable applications.

Q30. Explain the difference between arrays and linked lists with suitable examples.
Feature Array Linked List
Elements are stored together in Elements can be stored in different
Storage
memory memory locations
Access is slower because nodes are
Access Fast access using index
checked one by one
Slower because elements may need to
Insert/Delete Easier because links can be changed
be shifted
Size Usually fixed Can grow or shrink during execution
Example int arr[5] = {1,2,3,4,5}; 1 → 2 → 3 → 4 → 5 → NULL
Memory
Uses less extra memory Needs extra memory for links (pointers)
Use
Summary:
 Array is best when data size is known and fast access is needed.

 Linked List is best when data is frequently added or removed and the size changes often.
Q31. What is Programming Problem Solving? Explain its importance in software
development.
Programming Problem Solving is the process of understanding a problem, finding a solution,
writing code, testing it, and improving it when needed. It helps programmers solve different
types of real-life and software-related problems using logical thinking and programming skills.
Importance in Software Development:
1. It helps developers solve problems step by step.
2. It improves logical and analytical thinking.
3. It helps create faster and more efficient programs.
4. It is useful for programming tests and job interviews.
5. It increases confidence and coding ability.
6. It helps find and fix software errors more easily.
7. It improves decision-making during development.
8. It helps developers build reliable and high-quality software.
Programming problem solving is a fundamental skill because every software system is built by
solving problems.

Q32. Define recursion. Explain recursive and iterative approaches with examples.
Recursion, Recursive and Iterative Approaches
Recursion is a programming technique where a function calls itself again and again until a
stopping condition is reached. It is useful for solving problems that can be divided into smaller
similar problems.
Recursive Approach: A function solves a problem by calling itself. For example, finding the
factorial of a number using a recursive function.
Iterative Approach: A problem is solved using loops such as for or while. For example,
factorial can be calculated using a loop.
Differences: Recursion usually produces shorter code and is useful for tree-related problems.
Iteration is generally faster, uses less memory, and is preferred for better performance.

Q33. What is debugging? Discuss common debugging strategies used by programmers.


What is Debugging?
Debugging is the process of finding, analyzing, and fixing errors (bugs) in a program. It helps
programmers identify problems, improve program performance, and ensure that the software
works correctly and produces the expected results.
Common Debugging Strategies:
[Link] Debugging — print variable values to check program behavior.
[Link] a Debugger — use tools to find and examine errors.
[Link] Duck Debugging — explain the code step by step to find mistakes.
[Link] and Conquer — check small parts of the code separately.
[Link] Review — ask others to review the code.
[Link] Testing — test each function individually to find problems.
[Link] Error Messages — read error messages carefully to identify the cause.
[Link] Analysis — examine log files to track program activities and errors.
[Link] the Bug — run the same steps again to understand the problem better.

Q34. What is competitive programming? Discuss its benefits for problem solving skills.
Competitive Programming and Its Benefits
Competitive Programming is an activity where programmers solve coding problems within a
limited time. Participants write programs to solve problems and submit them to online platforms
such as Codeforces, LeetCode, HackerRank, and CodeChef.
Benefits for Problem Solving Skills:
1. Improves logical and algorithmic thinking.
2. Increases coding speed and accuracy.
3. Builds knowledge of data structures and algorithms.
4. Improves debugging and analytical skills.
5. Helps in programming contests and job interviews.
6. Encourages learning from other programmers.
7. Increases confidence in solving complex problems.
Competitive programming helps programmers become better problem solvers and software
developers.

Q35. Compare online judges such as CodeChef, UVa, and HackerRank.


Comparison of CodeChef, UVa, and HackerRank
Feature CodeChef UVa Online Judge HackerRank
Competitive Classic algorithm Skill learning and interview
Focus
programming contests problems preparation
Difficulty Beginner to Expert Intermediate to Expert Beginner to Advanced
Large and active Older but respected Large professional
Community
community community community
Regular contests and Practice of classic
Best For Coding interviews and jobs
ratings problems
Frequent programming Some contests and
Contests No regular contests
contests challenges
Feature CodeChef UVa Online Judge HackerRank
Learning Mainly problem Learning tracks and
Tutorials and discussions
Support solving tutorials
Company Widely used for
Limited Not focused on hiring
Hiring recruitment
Each platform has different strengths. CodeChef is good for contests, UVa is famous for classic
problems, and HackerRank is popular for learning programming and preparing for job
interviews.
Q36. Explain how online judges evaluate solutions. Discuss common mistakes made
during programming contests.
Online judges check solutions automatically. After a programmer submits code, the system runs
it on hidden test cases. If the output is correct and the program stays within the time and
memory limits, the result is Accepted (AC). Other results include Wrong Answer (WA), Time
Limit Exceeded (TLE), Runtime Error (RE), Memory Limit Exceeded (MLE), and
Compilation Error (CE).
Common Contest Mistakes:
1. Wrong logic or missing edge cases.
2. Slow algorithms causing TLE.
3. Using incorrect data types.
4. Loop boundary mistakes.
5. Misunderstanding the problem statement.
6. Not testing special cases.
7. Typing or syntax errors.
8. Incorrect input or output format.

Q37. What is lambda expression in C++? Write its syntax with example.
What is Lambda Expression in C++?
A lambda expression is a small unnamed function introduced in C++11. It can be written
directly inside the code without creating a separate function. Lambda expressions make
programs shorter, cleaner, and easier to understand.
Syntax:
[capture](parameters) {
// code
};
Example:
auto square = [](int x) {
return x * x;
};

cout << square(5);


Output: 25
Lambda expressions are commonly used with STL functions such as sort(), for_each(), and
other algorithms. They help programmers write simple and efficient code.

Q38. What is modular arithmetic? Explain its applications in programming contests.


Modular Arithmetic and Its Applications
Modular arithmetic is a method of calculation where numbers are divided by a fixed value
(modulus) and the remainder is used as the result. For example, 7 mod 3 = 1 because the
remainder is 1.
In programming contests, modular arithmetic is used when numbers become very large. It helps
keep numbers small and prevents calculation errors caused by large values. It is commonly used
in counting problems, combinations, permutations, dynamic programming, graph problems, and
power calculations. Modular arithmetic makes calculations faster and easier, which is very
important for solving programming contest problems efficiently.

Q39. Write the algorithm of Euclidean GCD method.


What is Euclidean GCD Method?
The Euclidean GCD Method is a simple and efficient way to find the Greatest Common Divisor
(GCD) of two numbers by repeatedly using division and taking remainders.
Algorithm:
1. Input two numbers a and b.
2. Check whether b = 0.
3. If b = 0, return a as the GCD and stop.
4. Otherwise, calculate the remainder r = a mod b.
5. Replace a with b and b with r.
6. Repeat Steps 2–5 until b = 0.
7. The final value of a is the GCD.
Example:
GCD(56, 98) → GCD(98, 56) → GCD(56, 42) → GCD(42, 14) → GCD(14, 0)
Answer: 14.

Q40. What is STL in C++? Explain the role of STL in competitive programming.
What is STL in C++?
STL (Standard Template Library) is a built-in library in C++ that provides ready-made data
structures and algorithms. It includes containers such as vector, map, set, stack, and queue,
along with useful functions like sort(), find(), and reverse().
Role of STL in Competitive Programming:
1. Saves time because common structures are already available.
2. Reduces coding errors.
3. Provides fast and efficient performance.
4. Makes code shorter and easier to read.
5. Helps manage and search data easily.
6. Supports easy traversal using iterators.
7. Useful for solving contest problems quickly.
STL is an essential tool for competitive programmers because it makes coding faster, simpler,
and more efficient.

Q41. Explain pair and tuple in STL. Write a program using STL stack to check balanced
parentheses.
Pair and Tuple in STL
A pair is an STL container that stores two values in a single variable. The two values can be of
the same or different data types and can be accessed using first and second.
Example:
pair<int, string> p = {1, "Hello"};
Values can be accessed using [Link] and [Link].
A tuple is similar to a pair but can store three or more values.
Example:
tuple<int, int, string> t = {1, 2, "OK"};
Program Using STL Stack to Check Balanced Parentheses
Algorithm:
1. Read each character of the expression.
2. If the character is '(', push it into the stack.
3. If the character is ')', check the stack.
4. If the stack is empty, parentheses are not balanced.
5. Otherwise, pop one element from the stack.
6. After checking all characters, if the stack is empty, parentheses are balanced.
stack<char> s;
for(char c : str){
if(c == '(')
[Link](c);
else if(c == ')'){
if([Link]())
return false;
[Link]();
}
}
return [Link]();

Q42. Define smart pointers. Differentiate between unique_ptr and shared_ptr.


Smart Pointers
Smart pointers are special C++ pointers that automatically manage memory. They free memory
when it is no longer needed, helping to prevent memory leaks and making programs safer and
easier to manage.
Feature unique_ptr shared_ptr
Ownership Only one owner is allowed Multiple owners are allowed
Reference
No reference counting Uses reference counting
Count
Memory Memory is freed when the pointer goes Memory is freed when the last owner
Freeing out of scope is removed
Copying Cannot be copied, only moved Can be copied and shared
For resources shared by many
Use Case For resources with a single owner
objects
Slightly slower due to reference
Performance Faster and lighter
counting
Memory Usage Uses less memory Uses more memory
Safety Prevents accidental sharing Allows safe shared ownership
Smart pointers help manage memory automatically. unique_ptr is best when only one object
owns a resource, while shared_ptr is useful when multiple objects need to use the same
resource.

Q43. What is computational geometry? Explain distance formula between two points in
2D geometry.
Computational Geometry and Distance Formula in 2D
Computational Geometry is a branch of computer science that deals with solving geometric
problems using algorithms. It works with points, lines, circles, polygons, and other shapes. It is
used in computer graphics, maps, GPS systems, robotics, and game development. In
programming contests, geometry problems often involve finding distances, areas, angles, and
intersections.
Distance Formula Between Two Points in 2D Geometry
The distance formula is used to find the straight-line distance between two points on a
coordinate plane. For two points P₁(x₁, y₁) and P₂(x₂, y₂), the distance is:

This formula comes from the Pythagorean Theorem. First, we find the horizontal difference
(x₂ − x₁) and vertical difference (y₂ − y₁) between the two points. These form the two sides of a
right triangle. The distance between the points is the hypotenuse of that triangle.
Example: P₁(1,2) and P₂(4,6)
Distance = √((4−1)² + (6−2)²) = √(9 + 16) = √25 = 5

Q44. Discuss applications of geometry problems in competitive programming, graphics


and games.
Geometry is widely used in competitive programming, computer graphics, and game
development.
In Competitive Programming, geometry helps solve problems such as finding distances
between points, checking line intersections, finding areas of shapes, and determining whether a
point lies inside a polygon.
In Computer Graphics, geometry is used to draw and display shapes, images, and 3D objects
on the screen. It also helps in object transformations such as moving, rotating, and resizing.
In Game Development, geometry is used for collision detection, character movement,
pathfinding, camera positioning, and physics effects such as gravity and bouncing objects.
Geometry is important for creating accurate and realistic applications.

Q45. Define Catalan number. Discuss applications of Catalan numbers in combinatorics.


Define Catalan Number
A Catalan number is a special number sequence used to count different possible ways of
arranging or organizing things. It is commonly used in problems involving brackets, trees,
paths, and other counting problems.
Applications of Catalan Numbers:
1. Counting correct bracket combinations.
2. Finding different BST structures.
3. Counting ways to make triangles in a polygon.
4. Counting correct ways to use brackets in a math expression.
5. Solving many counting problems.
6. Counting handshakes that do not cross each other.
7. Counting special paths from one point to another.
8. Finding different full binary trees.
9. Counting different valid arrangements of objects.
Catalan numbers are very useful in mathematics, algorithms, and competitive programming.

Q46. What is profiling? Explain memory profiling and CPU profiling.


Profiling, Memory Profiling, and CPU Profiling
Profiling is the process of checking a program's performance to find which parts use the most
time or memory. It helps programmers improve the speed and efficiency of a program.
CPU Profiling:
CPU profiling measures how much time each function or part of a program takes to run. It helps
find slow sections of code that need optimization.
Memory Profiling:
Memory profiling measures how much memory a program uses. It helps find memory leaks,
unnecessary memory usage, and objects that are not released properly.
Both CPU profiling and memory profiling help developers create faster, more stable, and
efficient software.

Q47. Define Pascal's Triangle. Explain relationship between Pascal's Triangle and
combinations.
Pascal's Triangle and Its Relationship with Combinations
Pascal's Triangle is a triangular pattern of numbers. The first row starts with 1, and each new
number is found by adding the two numbers directly above it.
Example:
1
11
121
1331
14641
Relationship with Combinations:
Each number in Pascal's Triangle represents a combination value C(n, k). It shows the number
of ways to choose k items from n items.
For example, the row 1 4 6 4 1 represents:
C(4,0), C(4,1), C(4,2), C(4,3), C(4,4)
Pascal's Triangle helps us find combination values easily without using large factorial
calculations. It is widely used in mathematics, probability, counting problems, and competitive
programming.

Q48. Explain Sieve of Eratosthenes with example.


Sieve of Eratosthenes with Example
The Sieve of Eratosthenes is a simple and fast method used to find all prime numbers from 2
to N by removing numbers that are multiples of other numbers.
Steps:
7. Create a list of numbers from 2 to N.
8. Start with 2, the first prime number.
9. Mark all multiples of 2 as not prime.
[Link] to the next unmarked number (3) and mark its multiples.
[Link] this process until all necessary numbers are checked.
[Link] remaining unmarked numbers are prime numbers.
Example (N = 20):
 Mark multiples of 2 → 4, 6, 8, 10, 12, 14, 16, 18, 20

 Mark multiples of 3 → 9, 15

Prime Numbers: 2, 3, 5, 7, 11, 13, 17, 19


This method is widely used in competitive programming for prime number problems.

Q49. What is function template in C++? Discuss the role of templates in competitive
programming.
Function Template in C++ and Its Role in Competitive Programming
A function template is a special function that can work with different data types using the
same code. This means we do not need to write separate functions for int, float, or double.
Example:
template <typename T>
T maxVal(T a, T b){
return (a > b) ? a : b;
}
This function can work with different data types.
Role of Templates in Competitive Programming:
1. Reduces code repetition.
2. Makes code shorter and easier to write.
3. Saves time during contests.
4. Helps create reusable functions and data structures.
5. Makes programs more flexible.
6. STL containers such as vector, stack, and queue are built using templates.
7. Allows the same function to work with different data types.
8. Reduces the chance of coding mistakes.
9. Makes code easier to maintain and understand.
Templates are very useful for writing clean, simple, reusable, and efficient code in competitive
programming.

Q50. Explain permutation with repetition. Solve a sample counting problem using
combinations.
Permutation with Repetition and Combination Example
Permutation with repetition means arranging items where the same item can be used more
than once. If there are n choices and r places, the number of possible arrangements is:

Example:
How many 3-digit PINs can be made using digits 0–9?
Answer: 10³ = 1000
Sample Problem Using Combination
A combination is used when choosing items and the order is not important.
Formula:
C(n,r) = n! / [r!(n-r)!]
Example:
A class has 10 students. How many ways can we choose a team of 3 students?
C(10,3) = (10×9×8)/(3×2×1) = 120
Answer: 120 ways
Permutations and combinations are useful for solving counting and selection problems in
mathematics and programming.

Q51. Write short note on: i) Compiler Error ii) Runtime Error iii) Logical Error
i) Compiler Error:
A compiler error happens when the code breaks the rules of the programming language. The
compiler finds the error before the program runs. Common examples are missing semicolons,
undeclared variables, and incorrect syntax. The program cannot run until these errors are fixed.
ii) Runtime Error:
A runtime error happens while the program is running. The program compiles successfully but
stops or crashes during execution. Common examples include dividing by zero, accessing
invalid memory, or using an array index that is out of range.
iii) Logical Error:
A logical error happens when the program runs without crashing but produces the wrong result.
The code has no syntax errors, but the logic is incorrect. For example, using addition instead of
multiplication can give the wrong output.

Q52. What is dynamic memory allocation in C++? Explain memory leak and its
prevention techniques.
What is Dynamic Memory Allocation in C++?
Dynamic memory allocation is the process of creating memory while a program is running. In
C++, memory is allocated from the heap using the new keyword and released using the delete
keyword when it is no longer needed.
Example:
int* p = new int(5);
delete p;
What is Memory Leak?
A memory leak occurs when dynamically allocated memory is not released after use. As a
result, unused memory remains occupied, causing higher memory usage and possibly slowing
down or crashing the program over time.
Prevention Techniques:
1. Always use delete after new.
2. Use delete[] for dynamic arrays.
3. Use smart pointers such as unique_ptr and shared_ptr.
4. Use tools like Valgrind to detect memory leaks.
5. Prefer stack memory when possible.
6. Review code carefully to ensure all allocated memory is released.
These techniques help make programs more efficient, stable, and memory-safe.

Q53. Explain constructors and destructors in C++. Discuss copy constructor with
example.
Constructors and Destructors in C++
A constructor is a special function that is called automatically when an object is created. It is
used to give initial values to object data.
Example:
Car(string n){
name = n;
}
A destructor is a special function that is called automatically when an object is destroyed or
goes out of scope. It is used to free resources and clean up memory.
Example:
~Car(){
cout << "Car destroyed";
}
Copy Constructor
A copy constructor is called when one object is created from another object of the same class.
Example:
Car c2 = c1;
Here, c2 receives a copy of the values stored in c1. Copy constructors are useful when copying
objects safely, especially when dynamic memory is used.

Q54. What is TLE? Discuss common causes of Time Limit Exceeded (TLE) in
programming contests.
TLE (Time Limit Exceeded) is an error given by an online judge when a program takes more
time than the allowed limit to finish its work. This usually happens when the code is too slow
for large inputs.
Common Causes of TLE:
1. Using a slow algorithm for a large problem.
2. Too many nested loops.
3. Repeating the same calculation many times.
4. Using slow input/output methods.
5. Missing memoization in recursive programs.
6. Using inefficient data structures.
7. Processing unnecessary data inside loops.
8. Infinite loops caused by coding mistakes.
To avoid TLE, programmers should use efficient algorithms, fast data structures, and optimized
code.

You might also like