Try it first — give it 15 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
This is a Codeforces problem: read standard input, print to standard output.
A tiny programming language has one variable, x, which starts at 0. A program is n statements (1 ≤ n ≤ 150), one per line. Each statement is one of:
++XorX++: add 1 tox;--XorX--: subtract 1 fromx.
Run the program and print the final value of x.
Example:
2
X++
--Xx goes 0 → 1 → 0, so print 0.
Building the intuition
The obvious plan is to compare each statement with all four possibilities: "if it equals ++X or X++, add 1; else subtract 1". That works, and it's fine.
But look closely at the four strings:
| Statement | Index 0 | Index 1 | Index 2 |
|---|---|---|---|
++X | + | + | X |
X++ | X | + | + |
--X | - | - | X |
X-- | X | - | - |
The middle character is always part of the operator, wherever the X sits. So statement[1] alone tells you whether to add or subtract.
This "find the one character that decides" habit is worth building early. It makes string problems shorter, and there are fewer chances to mistype a long comparison.
The optimal approach
- Read
nand setx = 0. - Repeat
ntimes: read a statements. Ifs[1] == '+', dox += 1; otherwisex -= 1. - Print
x.
Reading the input
The statements contain symbols, not numbers, so read them as strings:
data = sys.stdin.read().split() # ["2", "X++", "--X"]
n = int(data[0])string s;
cin >> s; // reads "X++" as one stringString s = in.readLine().trim(); // in is a BufferedReader; one statement per lineconst data = require("fs").readFileSync(0, "utf8").split(/\s+/).filter(Boolean);In C++ and Java, s[1] / s.charAt(1) is a character, so compare it with '+' in single quotes. In Python and JavaScript it's a one-letter string, so "+" works.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
import sys
def main():
data = sys.stdin.read().split() # ["2", "X++", "--X"]
n = int(data[0])
x = 0
for s in data[1:n + 1]:
# In ++X, X++, --X and X-- the middle character is always the operator's
if s[1] == "+":
x += 1
else:
x -= 1
print(x)
main()#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
int x = 0;
for (int i = 0; i < n; i++) {
string s;
cin >> s;
// In ++X, X++, --X and X-- the middle character is always the operator's
if (s[1] == '+') { // a char, so single quotes
x++;
} else {
x--;
}
}
cout << x << '\n';
return 0;
}import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(in.readLine().trim());
int x = 0;
for (int i = 0; i < n; i++) {
String s = in.readLine().trim(); // trim drops a stray '\r' from Windows line endings
// In ++X, X++, --X and X-- the middle character is always the operator's
if (s.charAt(1) == '+') { // a char, so == is safe (unlike String ==)
x++;
} else {
x--;
}
}
System.out.println(x);
}
}// Codeforces: choose "Node.js" as the language
const data = require("fs").readFileSync(0, "utf8").split(/\s+/).filter(Boolean);
const n = Number(data[0]);
let x = 0;
for (let i = 1; i <= n; i++) {
const s = data[i];
// In ++X, X++, --X and X-- the middle character is always the operator's
if (s[1] === "+") {
x++;
} else {
x--;
}
}
console.log(x);Dry run
| Statement | s[1] | Action | x |
|---|---|---|---|
| (start) | 0 | ||
X++ | + | add 1 | 1 |
--X | - | subtract 1 | 0 |
Print 0.
Complexity
- Time: O(n). One character check per statement.
- Space: O(1). Just
xand the current statement.
Edge cases and traps
- Checking only
s[0]. ForX++,s[0]isX, so you'd treat it as a subtraction. - Comparing strings with
==in Java.s == "X++"compares references, not text. Uses.equals("X++"). Checkings.charAt(1)dodges the issue. - A stray
\rat the end of the line. Windows line endings can leaveX++\r.trim()andsplit()remove it. - Negative answers. If every statement subtracts,
xends at−n. That's fine,xis a normal signed integer.
Say it in the interview
"There are only four statements, and in all of them the middle character belongs to the operator. So I start x at 0, and for each statement add 1 if the middle character is a plus and subtract 1 otherwise. That's one check per line, linear time and constant space."
Follow-ups interviewers ask
- "What if statements could be
X+=5orX-=3?" Now the middle trick breaks. Find the operator, then parse the number after it. - "What if there were several variables?" Keep a hash map from variable name to value. You will meet hash maps in the Arrays & Hashing stage.
Practise the same idea
This is Day 8 of a free 90-day plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free