Problem solving is the heart of programming. It’s not just about writing code — it’s about thinking logically, breaking down complex problems into simple steps, and developing a competitive mindset to solve problems efficiently. This skill is crucial for school exams, coding competitions (like CodeChef, LeetCode, Google Code Jam), and real-world software development.
This module covers:
- Logic Building – The foundation of problem solving
- Competitive Thinking – Advanced strategies for timed contests
Perfect for your C++ course — from Class 5 students learning basic patterns to BS students preparing for placement interviews.
Logic Building in C++
Logic building is the ability to think step-by-step and translate real-world problems into C++ code. It’s like solving a puzzle — you understand the pieces, then assemble them correctly.
What is Logic Building?
- Definition: Converting a problem description into a sequence of logical steps (algorithm) that a computer can follow.
- Why Important?: Even simple programs require logical thinking. Without it, you write random code that doesn’t work.
The Problem Solving Process (Step-by-Step)
Step 1: Understand the Problem
- Read the problem 3 times.
- Identify: Input (what goes in), Output (what comes out), Constraints (limits).
- Ask: “What does success look like?”
Example Problem: “Find the sum of first N natural numbers.”
- Input: N = 5
- Output: 15 (1+2+3+4+5)
- Constraints: 1 ≤ N ≤ 100
Step 2: Write Pseudocode
Pseudocode is like English instructions — no need for exact C++ syntax yet.
ALGORITHM SumNaturalNumbers:
INPUT: N (number of terms)
sum = 0
FOR i FROM 1 TO N:
sum = sum + i
OUTPUT: sum
ENDStep 3: Choose Data Structures
- Simple problems: Use basic variables (int, float) or arrays.
- Pattern problems: Use loops (for, while).
- String problems: Use string class.
Step 4: Write C++ Code
Convert pseudocode to actual C++.
#include <iostream>
using namespace std;
int main() {
int N;
cout << "Enter N: ";
cin >> N;
int sum = 0;
for (int i = 1; i <= N; i++) {
sum += i; // sum = sum + i
}
cout << "Sum = " << sum << endl;
return 0;
}Step 5: Test Your Solution
- Test with small inputs first (N=1, N=2).
- Check edge cases (N=0, N=100).
- Verify expected output.
Common Logic Building Patterns (For Class 5–12)
| Pattern Type | When to Use | Example Problems | C++ Tools Used |
|---|---|---|---|
| Basic Arithmetic | Simple calculations | Sum, average, factorial | int, float, loops |
| Pattern Printing | Visual patterns, loops practice | Triangle, pyramid, diamond | Nested for loops, cout |
| Array Processing | Lists of numbers/strings | Max/min, reverse, sort | Arrays, for loops |
| String Manipulation | Text processing | Palindrome, vowel count, reverse | string, char arrays |
| Recursion | Problems with self-similar structure | Factorial, Fibonacci, Tower of Hanoi | Recursive functions |
Pattern Printing Examples (Great for Class 5–10)
1. Right Triangle (Class 5–7)
*
**
***
****#include <iostream>
using namespace std;
int main() {
int rows = 4;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
cout << "*";
}
cout << endl; // New line after each row
}
return 0;
}2. Number Triangle (Class 8–10)
1
12
123
1234for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= i; j++) {
cout << j; // Print numbers 1 to i
}
cout << endl;
}Practice Problems for Logic Building
| Level | Problem Type | Difficulty | Time to Solve |
|---|---|---|---|
| Class 5–7 | Basic arithmetic, simple patterns | Easy | 10–15 min |
| Class 8–10 | Array processing, string patterns | Medium | 20–30 min |
| Class 11–12 | Recursion, two-pointer technique | Hard | 30–45 min |
Starter Problems:
- Print first 10 Fibonacci numbers
- Check if a number is prime
- Find largest of three numbers
- Reverse a string without using reverse() function
Competitive Thinking
Competitive programming trains you to solve problems quickly and efficiently under time pressure. It’s like mental gymnastics for programmers.
What is Competitive Programming?
- Definition: Solving algorithmic problems within time limits (usually 1–2 hours).
- Platforms: CodeChef, LeetCode, HackerRank, Codeforces, AtCoder
- Benefits: Improves problem-solving, coding speed, interview preparation
Competitive Thinking Strategies
1. The 3-Question Framework
For every problem, ask:
- What data structure? (array, vector, map, stack, queue)
- What algorithm? (sorting, searching, dynamic programming, greedy)
- What complexity? (O(n), O(n²), O(log n) — must fit time limit)
2. Input-Output Analysis
Always start here — 80% of competitive problems are solved by understanding I/O correctly.
Example Problem: “Given N numbers, find their sum”
Input:
First line: N (number of test cases)
For each test case:
First line: T (numbers in this test case)
Second line: T integers
Output:
For each test case, print the sumint main() {
int N;
cin >> N; // Number of test cases
for (int test = 0; test < N; test++) {
int T;
cin >> T; // Numbers in this test case
long long sum = 0; // Use long long for large sums
for (int i = 0; i < T; i++) {
int num;
cin >> num;
sum += num;
}
cout << sum << endl;
}
return 0;
}3. Brute Force First, Optimize Later
Strategy: Write a simple solution first (even if slow), then optimize.
Example: Find two numbers in array that sum to target
// Brute Force - O(n²) - Good for small N
for (int i = 0; i < n; i++) {
for (int j = i+1; j < n; j++) {
if (arr[i] + arr[j] == target) {
return {i, j};
}
}
}
// Optimized - O(n) using hash map (BS level)
unordered_map<int, int> seen;
for (int i = 0; i < n; i++) {
int complement = target - arr[i];
if (seen.count(complement)) {
return {seen[complement], i};
}
seen[arr[i]] = i;
}Common Competitive Programming Patterns
| Problem Type | Technique Used | Time Complexity | Example Problems |
|---|---|---|---|
| Sorting Problems | sort() function | O(n log n) | Closest numbers, median finding |
| Two Pointers | Left + right pointers | O(n) | Subarray sum, pair sum |
| Sliding Window | Dynamic window size | O(n) | Maximum sum subarray of size K |
| Binary Search | Divide and conquer | O(log n) | Find first/last occurrence |
| Dynamic Programming | Memoization/Tabulation | O(n) or O(n²) | Fibonacci, knapsack, LCS |
Fast Input/Output for Competitions
Default cin/cout can be slow for large inputs. Use these optimizations:
// Fast I/O Setup
#include <iostream>
#include <ios>
using namespace std;
int main() {
ios_base::sync_with_stdio(false); // Disable sync with C stdio
cin.tie(NULL); // Untie cin from cout
int n;
cin >> n;
// ... rest of code
}Debugging in Competitions (Time-Saver!)
| Situation | Quick Debug Technique |
|---|---|
| Wrong Answer | Add cout statements to trace variables |
| Time Limit Exceeded | Check loop complexity (O(n²) → O(n log n)) |
| Runtime Error | Check array bounds, null pointers |
| No Output | Verify cout statements, endl usage |
Practice Roadmap (For Your Website)
Phase 1: Logic Building (1 Month)
- Week 1–2: Basic patterns, loops, conditionals
- Week 3–4: Arrays, strings, simple recursion
Daily Practice: 2–3 problems, 30–45 minutes
Phase 2: Competitive Thinking (2 Months)
- Week 5–8: Sorting, searching, two-pointers
- Week 9–12: Dynamic programming, greedy algorithms
Weekly Practice: 10–15 problems + 1 full contest
Phase 3: Contest Preparation (Ongoing)
- Participate in weekly contests (CodeChef Starters, LeetCode Weekly)
- Analyze mistakes from previous contests
- Learn from editorial solutions
Sample Competitive Problem: “Chef and Snacks”
Problem: Chef has N snacks, each with cost Ci and rating Ri. He wants to buy exactly K snacks with maximum total rating within budget B.
Constraints:
- 1 ≤ N ≤ 1000
- 1 ≤ K ≤ N
- 1 ≤ Ci, Ri ≤ 1000
- 1 ≤ B ≤ 10^6
Approach:
- Calculate rating per cost: Ri/Ci
- Sort snacks by this ratio (descending)
- Pick top K snacks if total cost ≤ B
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int T;
cin >> T; // Test cases
while (T--) {
int N, K, B;
cin >> N >> K >> B;
vector<pair<double, int>> snacks; // {rating/cost, index}
for (int i = 0; i < N; i++) {
int C, R;
cin >> C >> R;
snacks.push_back({(double)R/C, i});
}
// Sort by rating/cost ratio (descending)
sort(snacks.rbegin(), snacks.rend());
int total_cost = 0;
int count = 0;
// Pick top K snacks
for (int i = 0; i < min(K, N); i++) {
// Find actual cost of this snack
int idx = snacks[i].second;
// ... (need to store costs separately)
// For simplicity, assume we track costs
if (total_cost <= B) {
count++;
} else {
break;
}
}
cout << count << endl;
}
return 0;
}