A - 本棚の整理 / Organizing the Bookshelf Editorial by admin
Qwen3-Coder-480BOverview
Among the books lined up on a bookshelf, find the position of the leftmost book that has a specified management number.
Analysis
This problem simply requires finding the leftmost position (the smallest index) among elements with value \(K\) in the given sequence \(A_1, A_2, \ldots, A_N\).
A straightforward approach is to check the books from left to right, and output the position as soon as we find the first book with management number \(K\). This is a basic technique called linear search, and it works without any issues.
The key point is that since we need to find the “smallest position,” it is sufficient to output the answer and terminate as soon as we find the first occurrence. Additionally, in case no such book exists, we need to output \(-1\) if the search reaches the end without finding one.
In this problem, the constraint is \(N \leq 2 \times 10^5\), so a brute-force search is fast enough (as a rough guideline, Python can handle up to about \(10^8\) operations). Therefore, more complex algorithms (such as binary search) are not necessary.
Algorithm
- Read \(N\), \(K\), and the sequence \(A\) from input.
- Scan \(A_i\) from left to right and find the smallest \(i\) such that \(A_i = K\).
- If found, output \(i+1\) (the 1-indexed position) and terminate the program.
- If not found after checking all elements, output \(-1\).
Complexity
- Time complexity: \(O(N)\)
- Space complexity: \(O(N)\)
*Storing the input array requires \(O(N)\), and the search itself also takes \(O(N)\) in the worst case since it may check all elements.
Implementation Notes
In Python, you can use
exit()to immediately terminate the program. This allows you to stop processing as soon as the first match is found.Note that indices are 0-based, but the output should be 1-based.
Source Code
N, K = map(int, input().split())
A = list(map(int, input().split()))
for i in range(N):
if A[i] == K:
print(i + 1)
exit()
print(-1)
This editorial was generated by qwen3-coder-480b.
posted:
last update: