Skip to main content

Arrays

Declaring and initializing arrays

// Static array
int arr[100005];

// Initialize all to zero
int arr[100005] = {};
memset(arr, 0, sizeof(arr));

// Vector (dynamic array) — preferred in CP
vector<int> v;           // Empty
vector<int> v(n);        // Size n, all zeros
vector<int> v(n, -1);    // Size n, all -1
vector<int> v = {1, 2, 3, 4, 5};

Common array operations

vector<int> v = {5, 3, 1, 4, 2};

// Add / remove elements
v.push_back(10);        // Add to end
v.pop_back();           // Remove last

// Access
v[0];                   // First element
v.front();              // First element
v.back();               // Last element
v.size();               // Number of elements

// Sort
sort(v.begin(), v.end());          // Ascending
sort(v.begin(), v.end(), greater<int>()); // Descending

// Reverse
reverse(v.begin(), v.end());

// Find min/max
int mn = *min_element(v.begin(), v.end());
int mx = *max_element(v.begin(), v.end());

// Sum
long long sum = accumulate(v.begin(), v.end(), 0LL);

2D arrays

int grid[105][105];

// Read a 2D grid
for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++)
        cin >> grid[i][j];

// 2D vector
vector<vector<int>> grid(n, vector<int>(m, 0));

Strings

Basic string operations

string s;
cin >> s;              // Read a word (stops at space)
getline(cin, s);       // Read entire line

s.length();            // or s.size()
s[i];                  // Character at index i
s += "abc";            // Concatenation
s.substr(pos, len);    // Substring from pos, length len
s.find("abc");         // Find substring (returns npos if not found)

Character operations

char c = 'A';

// Check character type
isalpha(c);    // Is letter?
isdigit(c);    // Is digit?
isupper(c);    // Is uppercase?
islower(c);    // Is lowercase?

// Convert
tolower(c);    // 'a'
toupper(c);    // 'A'

// Character to int
int digit = c - '0';    // If c is '5', digit = 5
int pos = c - 'a';      // If c is 'c', pos = 2

Character frequency counting

string s;
cin >> s;

int freq[26] = {};
for (char c : s) {
    freq[c - 'a']++;
}

// Print frequencies
for (int i = 0; i < 26; i++) {
    if (freq[i] > 0) {
        cout << (char)('a' + i) << ": " << freq[i] << "\n";
    }
}

Palindrome check

bool isPalindrome(string& s) {
    int l = 0, r = s.size() - 1;
    while (l < r) {
        if (s[l] != s[r]) return false;
        l++; r--;
    }
    return true;
}

String to number and vice versa

// String to int
string s = "123";
int n = stoi(s);       // 123
long long n = stoll(s); // For large numbers

// Number to string
int n = 123;
string s = to_string(n); // "123"

Common patterns

Reverse a string

string s = "hello";
reverse(s.begin(), s.end()); // "olleh"

Count occurrences of a character

int count = 0;
for (char c : s) {
    if (c == 'a') count++;
}
// Or using STL
int count = count(s.begin(), s.end(), 'a');

Split by delimiter (manual)

string s = "hello world foo";
stringstream ss(s);
string word;
while (ss >> word) {
    cout << word << "\n";
}
Arrays and strings are the foundation of every CP problem. Make sure you can manipulate them confidently before moving to more advanced topics.

Practice

Sheet 3: Arrays and Strings

Practice problems for this tutorial.