SC 428 · Introduction to C++ and the STL
// Lecture 3
Vectors Recap and Strings
Kalp Shah · IIT Gandhinagar · 2 November 2026
Today
Recap, two new topics, then practice
01
Vectors recap
Operations, their costs, 2D vectors, references
02
Strings
Declaring, reading input, indexing, joining, comparing, characters
03
Useful functions
substr, find, insert, erase, conversions, sort in depth, accumulate
04
Practice
Fourteen problems, each with a problem slide and a solution slide
SC 428 · Lecture 3 · Practice slides have a blue-grey background
01
Vectors recap
what we covered in Lecture 2
Vectors recap
A vector is an array that can grow
#include <vector> vector<int> v;                    // empty vector<int> w(5, 0);              // five zeros v.push_back(10);                  // {10} v.push_back(20);                  // {10, 20} cout << v.size();                 // 2 cout << v[0] << " " << v.back();  // 10 20 v.pop_back();                     // {10} for (int i = 0; i < v.size(); i++) {     cout << v[i] << " "; }
v[i] and v.back() read an element.
push_back and pop_back change the end.
size() always knows the current length.
SC 428 · Lecture 3 · Vectors recap
Vectors recap
What each operation costs
Operation
Cost
v[i], v.back(), v.size()
O(1)
push_back
amortized O(1)
pop_back
O(1)
insert / erase in the middle
O(n)
insert / erase at the front
O(n)
copy, or pass by value
O(n)
Rule of thumb
Work at the back is cheap. Work at the front or in the middle shifts every element after it.
SC 428 · Lecture 3 · Vectors recap · Strings follow the same rules
Vectors recap
2D vectors and passing by reference
A grid of rows and columns
int rows = 3, cols = 4; vector<vector<int>> g(rows,     vector<int>(cols, 0)); g[1][2] = 5; cout << g.size();     // 3 rows cout << g[0].size();  // 4 columns
Each row is its own vector, indexed g[r][c].
References avoid copies
void addOne(vector<int>& v) {     for (int i = 0; i < v.size(); i++) {         v[i]++;     } } int total(const vector<int>& v) {     int sum = 0;     for (int i = 0; i < v.size(); i++) {         sum += v[i];     }     return sum; }
& lets the function change the caller’s vector. const & reads it without copying.
SC 428 · Lecture 3 · Vectors recap · The same rule applies to strings: pass them as const string&
Warm-up · Problem
uses: push_back, insert, erase, pop_back
Predict the output
vector<int> v = {3, 1, 4}; v.push_back(1); v.insert(v.begin() + 1, 5); v.erase(v.begin()); v.pop_back(); cout << v.size() << "\n"; for (int i = 0; i < v.size(); i++) {     cout << v[i] << " "; }
Task
Without running it, write down what this program prints.
Track the vector after every line.
SC 428 · Lecture 3 · Warm-up
Warm-up · Solution
Predict the output
Statement
v afterwards
vector<int> v = {3, 1, 4};
{3, 1, 4}
v.push_back(1);
{3, 1, 4, 1}
v.insert(v.begin() + 1, 5);
{3, 5, 1, 4, 1}
v.erase(v.begin());
{5, 1, 4, 1}
v.pop_back();
{5, 1, 4}
Output
3 5 1 4
insert puts 5 before index 1. erase(v.begin()) removes the first element.
SC 428 · Lecture 3 · Warm-up
02
Strings
text as a sequence of characters
Strings
A string is a sequence of characters
#include <string> string name = "Asha"; string empty;                  // "" cout << name.length();         // 4 cout << name[0];               // A cout << name.back();           // a name[0] = 'U';                 // "Usha" cout << name;                  // Usha
A
name[0]
s
[1]
h
[2]
a
[3]
  • Works like a vector of char: indices 0 to length − 1.
  • Single quotes for one character: 'A'. Double quotes for text: "A".
  • length() and size() give the same number.
SC 428 · Lecture 3 · Strings · An index outside 0 to length − 1 is undefined, as with arrays
Strings
cin reads one word; getline reads a whole line
cin >> stops at a space
string word; cin >> word;  // input: New Delhi cout << word; // New
getline keeps the spaces
string line; getline(cin, line);  // input: New Delhi cout << line;        // New Delhi
Trap: a number, then a line
int age; string name; cin >> age; cin.ignore();  // skip the leftover Enter getline(cin, name);
Why cin.ignore()?
After cin >> age, the Enter key is still waiting in the input. Without cin.ignore(), getline reads that empty line and name stays empty.
SC 428 · Lecture 3 · Strings
Strings
Joining and comparing strings
+ and += join text
string first = "Ada"; string last = "Lovelace"; string full = first + " " + last; cout << full;        // Ada Lovelace full += "!";         // Ada Lovelace! full.push_back('?'); // Ada Lovelace!?
== and < compare text
string a = "apple"; string b = "banana"; string c = "Zebra"; if (a < b) {     cout << "apple first\n";  // printed } if (c < a) {     cout << "Zebra first\n";  // printed }
Dictionary order, letter by letter. Every capital letter comes before every small letter, so "Zebra" < "apple". A prefix comes first: "app" < "apple".
SC 428 · Lecture 3 · Strings
Strings
Looping over the characters
string s = "Hello World"; int n = s.length(); int spaces = 0; for (int i = 0; i < n; i++) {     if (s[i] == ' ') {         spaces++;     } } cout << spaces;       // 1 for (int i = 0; i < n; i++) {     if (s[i] == 'o') {         s[i] = '0';     } } cout << s;            // Hell0 W0rld
s[i] is a char. Compare it with single quotes: s[i] == ' '.
Strings can change in place. s[i] = '0' replaces one character.
for (char c : s) also visits each character, but changing c does not change s.
SC 428 · Lecture 3 · Strings · Storing s.length() in an int n keeps the loop simple
Strings · Characters
Every character is stored as a number
Character
Stored as
'A'
65
'Z'
90
'a'
97
'z'
122
'0'
48
'9'
57
char c = 'd'; int pos = c - 'a';           // 3 char upper = c - 'a' + 'A';  // 'D' char next = 'a' + 2;         // 'c' char digit = '7'; int value = digit - '0';     // 7
  • 'a' to 'z' are consecutive, so c − 'a' is a position from 0 to 25.
  • '0' to '9' are consecutive, so digit − '0' is the digit’s value.
SC 428 · Lecture 3 · Strings · These numbers are the ASCII codes
Strings · Characters
Checking and changing characters
Function
Meaning
isalpha(c)
c is a letter
isdigit(c)
c is '0' to '9'
isspace(c)
c is a space, tab or newline
isupper(c)
c is a capital letter
islower(c)
c is a small letter
toupper(c)
the capital version of c
tolower(c)
the small version of c
string s = "Hi 2026!"; int n = s.length(); int letters = 0; int digits = 0; for (int i = 0; i < n; i++) {     if (isalpha(s[i])) {         letters++;     }     if (isdigit(s[i])) {         digits++;     }     s[i] = toupper(s[i]); } cout << letters << " " << digits;  // 2 4 cout << s;                        // HI 2026!
SC 428 · Lecture 3 · Strings · #include <cctype> · toupper and tolower leave non-letters unchanged
03
Useful functions
string members · conversions · sort · accumulate
Useful functions · Strings
substr cuts out a part; find searches
h
0
e
1
l
2
l
3
o
4
·
5
w
6
o
7
r
8
l
9
d
10
string s = "hello world"; cout << s.substr(6);        // world cout << s.substr(0, 5);     // hello int pos = s.find("world");  // 6 int first = s.find('o');    // 4 if (s.find("xyz") == string::npos) {     cout << "not found"; }
substr(start, length): the second number is a length, not an end index. Leave it out to go to the end.
find gives the first position. Missing text gives string::npos: check before using the result.
SC 428 · Lecture 3 · Useful functions · Highlighted: s.substr(6) and s.find("world")
Useful functions · Strings
insert, erase and replace edit a string
string s = "I like C"; s.insert(7, "C++ and ");   // "I like C++ and C" s.erase(0, 2);             // "like C++ and C" s.replace(0, 4, "love");   // "love C++ and C" s.pop_back();              // "love C++ and " s.clear();                 // "" cout << s.empty();         // 1 (true)
Positions are plain numbers here, unlike vector insert and erase, which take v.begin() + i.
erase(i, len) and replace(i, len, t) take a start and a length, like substr.
Like vectors, editing the front or middle shifts the rest: O(n).
SC 428 · Lecture 3 · Useful functions
Useful functions · Strings
String members at a glance, with s = "hello"
Call
What it does
Result
s.length(), s.size()
number of characters
5
s.substr(1, 3)
3 characters starting at index 1
"ell"
s.find("l")
first position of "l", or string::npos
2
s.insert(1, "X")
insert "X" before index 1
"hXello"
s.erase(1, 2)
remove 2 characters starting at index 1
"hlo"
s.replace(0, 1, "J")
replace 1 character at index 0 with "J"
"Jello"
s.push_back('!')
add a character at the end
"hello!"
s.pop_back()
remove the last character
"hell"
s.empty()
is the string empty?
false
SC 428 · Lecture 3 · Useful functions · Each row starts again from s = "hello"
Useful functions · Conversions
Converting between text and numbers
int n = stoi("42");                       // 42 double d = stod("3.5");                   // 3.5 string s = to_string(2026);               // "2026" string label = "Year " + to_string(2026); // "Year 2026" int total = stoi("12") + stoi("30");      // 42
stoi turns text into an int; stod into a double.
to_string turns a number into text, so it can be joined with +.
stoi("abc") stops the program with an error: the text must start with a number.
SC 428 · Lecture 3 · Useful functions · For a single digit character, digit − '0' is enough
Useful functions · STL
The same STL functions work on vectors and strings
vector<int> v = {5, 2, 8, 1}; sort(v.begin(), v.end());                      // {1, 2, 5, 8} reverse(v.begin(), v.end());                   // {8, 5, 2, 1} string s = "banana"; sort(s.begin(), s.end());                      // "aaabnn" reverse(s.begin(), s.end());                   // "nnbaaa" int numA = count(s.begin(), s.end(), 'a');     // 3 char last = *max_element(s.begin(), s.end());  // 'n'
New: sort
Puts elements in increasing order. O(n log n), in <algorithm>.
On a string, sort orders the characters by their codes.
Decreasing order: sort, then reverse.
SC 428 · Lecture 3 · Useful functions · reverse, count and max_element are the Lecture 2 functions
Useful functions · sort
sort puts a range in increasing order
vector<int> v = {5, 2, 8, 1, 9}; sort(v.begin(), v.end());          // {1, 2, 5, 8, 9} vector<int> w = {5, 2, 8, 1, 9}; sort(w.begin(), w.begin() + 3);    // {2, 5, 8, 1, 9} int a[] = {4, 3, 1}; sort(a, a + 3);                    // {1, 3, 4} string s = "sort"; sort(s.begin(), s.end());          // "orst"
The range decides what is sorted: all of v, or only the first 3 elements of w.
Works on vectors, arrays and strings. It changes them in place.
Cost: O(n log n). For n = 10^6, about 2 × 10^7 steps.
SC 428 · Lecture 3 · Useful functions · #include <algorithm>
Useful functions · sort
Largest first, pairs, and strings
Largest first: two ways
vector<int> v = {5, 2, 8, 1}; sort(v.begin(), v.end()); reverse(v.begin(), v.end()); // {8, 5, 2, 1} vector<int> w = {5, 2, 8, 1}; sort(w.begin(), w.end(), greater<int>()); // {8, 5, 2, 1}
greater<int>() tells sort to put bigger values first.
Pairs and strings
vector<pair<int, int>> p =     {{2, 9}, {1, 5}, {2, 3}}; sort(p.begin(), p.end()); // {1, 5} {2, 3} {2, 9} vector<string> w = {"pear", "apple", "Apple"}; sort(w.begin(), w.end()); // Apple apple pear
Pairs: by first, then by second. Strings: dictionary order, capitals first.
SC 428 · Lecture 3 · Useful functions · greater<int>() needs #include <functional>
Useful functions · sort
What sorting gives you for free
After sorting n values
You get
v[0]
the smallest value
v[n - 1]
the largest value
v[n / 2]
the median, when n is odd
v[0] to v[k - 1]
the k smallest values
equal values
next to each other
the closest two values
always neighbours
Why it matters
Sorting first often turns a search over all pairs, O(n²), into one pass over neighbours.
SC 428 · Lecture 3 · Useful functions · Practice problems P9 and P11–P14 use these facts
Useful functions · accumulate
accumulate adds up a range
#include <numeric> vector<int> marks = {72, 85, 90, 64}; int total = accumulate(marks.begin(), marks.end(), 0); // 311 double avg = accumulate(marks.begin(), marks.end(), 0.0)              / marks.size(); // 77.75 int firstTwo = accumulate(marks.begin(), marks.begin() + 2, 0); // 157 int a[] = {1, 2, 3, 4}; int sum = accumulate(a, a + 4, 0);  // 10
accumulate(first, last, start)
Adds every element to start and returns the total. O(n).
The start sets the type
Start 0 adds whole numbers. Start 0.0 adds decimals, so the average keeps .75.
SC 428 · Lecture 3 · Useful functions · accumulate is in <numeric>, not <algorithm>
Useful functions · Vectors of strings
A vector can hold strings
vector<string> names = {"Ravi", "Asha", "Meera"}; names.push_back("Zoya"); sort(names.begin(), names.end()); int n = names.size(); for (int i = 0; i < n; i++) {     cout << names[i] << " " << names[i].length() << "\n"; } cout << names[0][0];  // A
Output of the loop
Asha 4 Meera 5 Ravi 4 Zoya 4
  • names[i] is a string; names[i][j] is one of its characters.
  • Sorting a vector of strings gives dictionary order.
SC 428 · Lecture 3 · Useful functions
04
Practice
fourteen problems · each with a solution slide
Practice P1 · Problem
uses: getline, loops, tolower, find
Count the vowels
Task
Read one line of text, which may contain spaces.
Print how many vowels (a, e, i, o, u) it contains. Count capital and small letters.
Examples
Hello World      -> 3 Programming In C -> 4 rhythm           -> 0
Hint: make each character small with tolower, then check whether it is one of the five vowels.
SC 428 · Lecture 3 · Practice
Practice P1 · Solution
code goes inside main(), with <iostream>, <string> and <cctype>
Count the vowels
string s; getline(cin, s); string vowels = "aeiou"; int total = 0; int n = s.length(); for (int i = 0; i < n; i++) {     char c = tolower(s[i]);     if (vowels.find(c) != string::npos) {         total++;     } } cout << total << "\n";
How it works
  1. getline keeps the spaces, so the whole line is read.
  2. tolower turns 'E' into 'e', so one check covers both cases.
  3. vowels.find(c) is not npos exactly when c is one of a, e, i, o, u.
SC 428 · Lecture 3 · Practice · O(n) time
Practice P2 · Problem
uses: indexing, reverse, comparing strings
Palindrome check
Task
Read one word in small letters.
Print YES if it reads the same forwards and backwards. Otherwise print NO.
Examples
racecar -> YES noon    -> YES abca    -> NO a       -> YES
Hint: try it two ways: with reverse from the STL, and with a loop that compares s[i] with s[n − 1 − i].
SC 428 · Lecture 3 · Practice
Practice P2 · Solution
code goes inside main(), with <iostream>, <string> and <algorithm>
Palindrome check
With reverse
string s; cin >> s; string reversed = s; reverse(reversed.begin(), reversed.end()); if (s == reversed) {     cout << "YES\n"; } else {     cout << "NO\n"; }
Short and clear, but makes a second copy of the word.
With a loop
string s; cin >> s; int n = s.length(); bool isPalindrome = true; for (int i = 0; i < n / 2; i++) {     if (s[i] != s[n - 1 - i]) {         isPalindrome = false;     } } if (isPalindrome) {     cout << "YES\n"; } else {     cout << "NO\n"; }
SC 428 · Lecture 3 · Practice · Both are O(n)
Practice P3 · Problem
uses: arrays as counters, c − 'a'
Count each letter
Task
Read one word made of small letters.
For each letter that appears, print the letter and how many times it appears, in alphabetical order.
Example
Input: banana Output: a 3 b 1 n 2
Hint: use an array of 26 counters, one for each letter. s[i] − 'a' tells you which counter to increase.
SC 428 · Lecture 3 · Practice
Practice P3 · Solution
code goes inside main(), with <iostream> and <string>
Count each letter
string s; cin >> s; int letterCount[26] = {0}; int n = s.length(); for (int i = 0; i < n; i++) {     int index = s[i] - 'a';     letterCount[index]++; } for (int i = 0; i < 26; i++) {     if (letterCount[i] > 0) {         char letter = 'a' + i;         cout << letter << " " << letterCount[i] << "\n";     } }
How it works
  1. letterCount[0] counts 'a', letterCount[1] counts 'b', and so on.
  2. s[i] − 'a' is 0 for 'a' and 13 for 'n'.
  3. 'a' + i turns a position back into a letter.
SC 428 · Lecture 3 · Practice · Assumes small letters only: a capital gives an index outside 0 to 25
Practice P4 · Problem
uses: getline, loops, empty
Count the words
Task
Read one line. Words are separated by single spaces, with no spaces at the start or end.
Print the number of words.
Examples
I love C plus plus -> 5 Hello             -> 1 (empty line)      -> 0
Hint: how is the number of spaces related to the number of words?
SC 428 · Lecture 3 · Practice
Practice P4 · Solution
code goes inside main(), with <iostream> and <string>
Count the words
string line; getline(cin, line); int words = 0; if (!line.empty()) {     words = 1; } int n = line.length(); for (int i = 0; i < n; i++) {     if (line[i] == ' ') {         words++;     } } cout << words << "\n";
How it works
  1. A non-empty line has at least one word.
  2. Each space starts one more word, so words = spaces + 1.
Limit: two spaces in a row would count an extra word. That is why the task promises single spaces.
SC 428 · Lecture 3 · Practice · O(n) time
Practice P5 · Problem
uses: getline, toupper, changing characters
Capitalise every word
Task
Read one line of small-letter words separated by single spaces.
Change the first letter of every word to a capital and print the line.
Example
Input: the quick brown fox Output: The Quick Brown Fox
Hint: a letter starts a word if it is the first character, or the character before it is a space.
SC 428 · Lecture 3 · Practice
Practice P5 · Solution
code goes inside main(), with <iostream>, <string> and <cctype>
Capitalise every word
string line; getline(cin, line); int n = line.length(); for (int i = 0; i < n; i++) {     if (i == 0 || line[i - 1] == ' ') {         line[i] = toupper(line[i]);     } } cout << line << "\n";
How it works
  1. A character starts a word if it is first, or comes right after a space.
  2. toupper changes only that character; the rest stay as they are.
  3. || checks i == 0 first, so line[i − 1] is never read when i is 0.
SC 428 · Lecture 3 · Practice · O(n) time
Practice P6 · Problem
uses: sort, comparing strings
Anagram check
Task
Read two words in small letters.
Print YES if one is a rearrangement of the other’s letters, using every letter exactly once. Otherwise print NO.
Examples
listen silent -> YES apple paple   -> YES rat car       -> NO ab abb        -> NO
Hint: what do two anagrams look like after you sort their letters?
SC 428 · Lecture 3 · Practice
Practice P6 · Solution
code goes inside main(), with <iostream>, <string> and <algorithm>
Anagram check
string a, b; cin >> a >> b; sort(a.begin(), a.end()); sort(b.begin(), b.end()); if (a == b) {     cout << "YES\n"; } else {     cout << "NO\n"; }
How it works
  1. Sorting puts each word’s letters in order: "listen" and "silent" both become "eilnst".
  2. Two words are anagrams exactly when their sorted forms are equal.
Another way: count both words’ letters with the 26 counters from P3 and compare the counts.
SC 428 · Lecture 3 · Practice · Sorting is O(n log n); counting letters is O(n)
Practice P7 · Problem
uses: find, string::npos, substr
Split an email address
Task
Read an email address with no spaces.
Print the part before the @ and the part after it, on separate lines. If there is no @, print Invalid.
Examples
Input: asha.rao@iitgn.ac.in Output: asha.rao iitgn.ac.in Input: hello.world Output: Invalid
Hint: find tells you where the @ is. The username’s length is exactly that position.
SC 428 · Lecture 3 · Practice
Practice P7 · Solution
code goes inside main(), with <iostream> and <string>
Split an email address
string email; cin >> email; if (email.find('@') == string::npos) {     cout << "Invalid\n"; } else {     int at = email.find('@');     cout << email.substr(0, at) << "\n";     cout << email.substr(at + 1) << "\n"; }
How it works
  1. Check for string::npos first: no @ means Invalid.
  2. In "asha.rao@iitgn.ac.in", the @ is at index 8.
  3. substr(0, 8) takes the 8 characters before it.
  4. substr(9) takes everything after it.
SC 428 · Lecture 3 · Practice · O(n) time
Practice P8 · Problem
uses: strings as numbers, digit − '0'
Digit sum of a very large number
Task
Read a positive whole number with up to 100 digits.
Print the sum of its digits.
Examples
2026 -> 10 98765432109876543210 -> 90
Hint: 100 digits do not fit in int or long long. Read the number as a string.
SC 428 · Lecture 3 · Practice
Practice P8 · Solution
code goes inside main(), with <iostream> and <string>
Digit sum of a very large number
string number; cin >> number; int sum = 0; int n = number.length(); for (int i = 0; i < n; i++) {     int digit = number[i] - '0';     sum += digit; } cout << sum << "\n";
How it works
  1. As text, the number can have any length.
  2. number[i] − '0' turns the character '7' into the number 7.
  3. The sum is at most 100 × 9 = 900, so int is enough for it.
SC 428 · Lecture 3 · Practice · O(n) time
Practice P9 · Problem
uses: vectors, sort, push_back
Distinct values in order
Task
Read n, then n integers into a vector.
Print each different value once, in increasing order.
Example
Input: 7 4 2 4 1 2 4 9 Output: 1 2 4 9
Hint: after sorting, equal values sit next to each other.
SC 428 · Lecture 3 · Practice
Practice P9 · Solution
code goes inside main(), with <iostream>, <vector> and <algorithm>
Distinct values in order
int n; cin >> n; vector<int> v(n); for (int i = 0; i < n; i++) {     cin >> v[i]; } sort(v.begin(), v.end()); vector<int> distinct; for (int i = 0; i < n; i++) {     if (i == 0 || v[i] != v[i - 1]) {         distinct.push_back(v[i]);     } } for (int i = 0; i < distinct.size(); i++) {     cout << distinct[i] << " "; }
How it works
  1. After sorting: 1 2 2 4 4 4 9.
  2. Keep a value if it is the first one, or differs from the one just before it.
  3. i == 0 is checked first, so v[i − 1] is never read at index 0, as in P5.
SC 428 · Lecture 3 · Practice · Sorting dominates: O(n log n)
Practice P10 · Problem
uses: vector of strings, sort, length
Sort the names, find the longest
Task
Read n, then n names, each one word.
Print the names in alphabetical order on one line. Then print the longest name. If several are equally long, print the one that comes first alphabetically.
Example
Input: 4 Ravi Asha Meera Zoya Output: Asha Meera Ravi Zoya Meera
Hint: sort first. Then finding the longest is the “best so far” loop from Lecture 2.
SC 428 · Lecture 3 · Practice
Practice P10 · Solution
inside main(), with <iostream>, <string>, <vector> and <algorithm>
Sort the names, find the longest
Part 1 · read, sort, print
int n; cin >> n; vector<string> names(n); for (int i = 0; i < n; i++) {     cin >> names[i]; } sort(names.begin(), names.end()); for (int i = 0; i < n; i++) {     cout << names[i] << " "; } cout << "\n";
Part 2 · the longest name
string longest = names[0]; for (int i = 1; i < n; i++) {     if (names[i].length() > longest.length()) {         longest = names[i];     } } cout << longest << "\n";
Why > and not >=? On a tie it keeps the earlier name, which after sorting is the alphabetically first one.
SC 428 · Lecture 3 · Practice · Sorting dominates: O(n log n)
Practice P11 · Problem
uses: vectors, sort
Median mark
Task
Read an odd number n, then n marks.
Print the median: the middle mark once the marks are in order.
Examples
5 70 45 90 60 85 -> 70 3 9 1 5          -> 5
Hint: after sorting, where is the middle element of a vector of size n?
SC 428 · Lecture 3 · Practice · Sorting problems
Practice P11 · Solution
code goes inside main(), with <iostream>, <vector> and <algorithm>
Median mark
int n; cin >> n; vector<int> marks(n); for (int i = 0; i < n; i++) {     cin >> marks[i]; } sort(marks.begin(), marks.end()); cout << marks[n / 2] << "\n";
How it works
  1. Sorted: 45 60 70 85 90.
  2. For n = 5 the indices are 0 to 4, so the middle is index 2 = 5 / 2.
  3. Integer division rounds down, so n / 2 is the middle for every odd n.
Even n: the median is the average of marks[n / 2 − 1] and marks[n / 2].
SC 428 · Lecture 3 · Practice · O(n log n)
Practice P12 · Problem
uses: sort, largest first
Top three scores
Task
Read n (at least 3), then n scores.
Print the three highest scores, largest first. A repeated score counts each time it appears.
Example
Input: 6 40 95 70 95 20 88 Output: 95 95 88
Hint: sort largest first, then the answer is at the front.
SC 428 · Lecture 3 · Practice · Sorting problems
Practice P12 · Solution
inside main(), with <iostream>, <vector>, <algorithm> and <functional>
Top three scores
int n; cin >> n; vector<int> scores(n); for (int i = 0; i < n; i++) {     cin >> scores[i]; } sort(scores.begin(), scores.end(), greater<int>()); for (int i = 0; i < 3; i++) {     cout << scores[i] << " "; }
How it works
  1. Largest first: 95 95 88 70 40 20.
  2. The first three elements are the answer.
Without greater: sort normally, then print scores[n − 1], scores[n − 2] and scores[n − 3].
SC 428 · Lecture 3 · Practice · O(n log n)
Practice P13 · Problem
uses: sort, neighbours, best so far
Smallest gap between two values
Task
Read n (at least 2), then n integers.
Print the smallest difference between any two of them.
Example
Input: 5 10 3 19 7 14 Output: 3
Hint: checking every pair works but is O(n²). After sorting, which pairs can be the closest?
SC 428 · Lecture 3 · Practice · Sorting problems
Practice P13 · Solution
code goes inside main(), with <iostream>, <vector> and <algorithm>
Smallest gap between two values
int n; cin >> n; vector<int> v(n); for (int i = 0; i < n; i++) {     cin >> v[i]; } sort(v.begin(), v.end()); int best = v[1] - v[0]; for (int i = 2; i < n; i++) {     int gap = v[i] - v[i - 1];     if (gap < best) {         best = gap;     } } cout << best << "\n";
How it works
  1. Sorted: 3 7 10 14 19. Gaps between neighbours: 4, 3, 4, 5.
  2. Any two values that are not neighbours have a value between them, so their gap is never smaller.
  3. Start best with the first gap, then keep the smallest.
SC 428 · Lecture 3 · Practice · O(n log n) instead of O(n²) for all pairs
Practice P14 · Problem
uses: sort, accumulate
Judges’ scores
Task
Read n (at least 3), then the n scores given by the judges.
Drop one highest and one lowest score, and print the average of the rest.
Examples
5 7 9 6 10 8 -> 8 4 3 8 7 10   -> 7.5
Hint: after sorting, the lowest and highest are at the two ends. accumulate can add up everything in between.
SC 428 · Lecture 3 · Practice · Sorting problems
Practice P14 · Solution
inside main(), with <iostream>, <vector>, <algorithm> and <numeric>
Judges’ scores
int n; cin >> n; vector<int> scores(n); for (int i = 0; i < n; i++) {     cin >> scores[i]; } sort(scores.begin(), scores.end()); double middleSum = accumulate(scores.begin() + 1,                               scores.end() - 1, 0.0); double average = middleSum / (n - 2); cout << average << "\n";
How it works
  1. Sorted: 3 7 8 10. The lowest is at the front, the highest at the back.
  2. begin() + 1 to end() − 1 skips both ends: 7 + 8 = 15.
  3. Start 0.0 makes the sum a double, so 15 / 2 gives 7.5, not 7.
SC 428 · Lecture 3 · Practice · O(n log n)
Recap
Six things to remember from today
Vectors
Work at the back is cheap. The front and middle cost O(n).
Strings
A string works like a vector of char: s[i], length(), push_back.
Input
cin >> reads one word; getline reads a whole line. Use cin.ignore() between them.
Characters
Characters are numbers: c − 'a' and digit − '0'.
substr and find
substr takes a start and a length. find returns string::npos when nothing matches.
STL
sort orders a range in O(n log n); accumulate adds it up. Both work on vectors, arrays and strings.