The First Conflicting Request
- Memory limit
- 256 MB
- Correctness time limit
- 20000 ms
- Solvers
- 0
There are n switches numbered 1..n, each on (true) or off (false). Requests arrive in the order of clauses; request
[x, y] means "at least one of x, y must hold", where a positive v means "switch v is on" and a negative -v means
"switch v is off". Both literals may name the same switch ([3, 3] forces switch 3 on; [2, -2] always holds).
Return the 0-based index of the first request after which no switch setting satisfies all requests so far, or -1 if all
requests can be satisfied together.
Examples
| n | clauses | result |
|---|---|---|
3 | [[1, 2], [-1, 3], [-2, -3], [-3, 1]] | -1 |
2 | [[1, 1], [-1, 2], [-2, -1], [2, 2]] | 2 |
2 | [[1, 2], [-1, 2], [1, -2], [-1, -2]] | 3 |
Example 1 — on/off/on satisfies everything.
Example 2 — request 0 forces switch 1 on, request 1 then forces switch 2 on, and request 2 can no longer hold.
Example 3 — the first three hold with both switches on; all four together rule out every setting.
Efficiency
This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.
Function signature
solution(n: int, clauses: int[][]) → int
Constraints
-
n -
clauses.length clauses[i] = [x, y],n(never0)
Expected complexity
- Time
- O((N + M) log M)
- Space
- O(N + M)
Examples
| n | clauses | Expected |
|---|---|---|
3 | [[1,2],[-1,3],[-2,-3],[-3,1]] | -1 |
2 | [[1,1],[-1,2],[-2,-1],[2,2]] | 2 |
2 | [[1,2],[-1,2],[1,-2],[-1,-2]] | 3 |
Hint
Hint
One check is 2-SAT: "a or b" becomes the implications not a -> b and not b -> a on a graph of literals; the requests
are satisfiable iff no switch has both literals in the same strongly connected component ( with Tarjan or Kosaraju).
Satisfiability of a prefix is monotone in its length, so binary search the first failing prefix with checks.
Re-checking after every request is and exceeds the time limit. DFS depth can reach , so prefer an
iterative DFS.
Time limits per language
| Language | Efficiency time limit | |
|---|---|---|
| C (GCC, gnu17) | 364 ms | estimated |
| C++ (GCC, gnu++23) | 364 ms | derived |
| Python 3.13 | 6948 ms | derived |
| Java 25 | 2034 ms | derived |
| Kotlin 2.4 (JVM) | 1728 ms | estimated |
| C# 14 (.NET 10) | 1728 ms | estimated |
Test groups
| Group | Weight | Tests | Visibility |
|---|---|---|---|
| sample | 0 | 3 | inputs and outputs |
| correctness | 40 | 12 | verdict only |
| performance | 60 | 4 | verdict only |