आसान 0 हल किए गए 0% स्वीकृति

Second Largest Value

Find the second largest distinct value.

आप क्या सीखेंगे

  • Track the top two values in one pass
  • Ignore duplicates of the maximum
  • Handle lists without a second value

समस्या

अनुवाद दिखाएँ

Return the second largest distinct value in the list. Repeated values count once.

Implement second_largest(numbers).

Input

numbers: A list of non-negative integers.

Output

Return the second largest distinct value, or -1 if it doesn't exist.

सीमाएँ

0 ≤ length ≤ 100,000; 0 ≤ each value ≤ 10⁹

उदाहरण

उदाहरण 1
इनपुट:
numbers = [4, 9, 7, 9]

अपेक्षित आउटपुट:
expected = 7
इनपुट:
std::vector<long long> numbers = {4, 9, 7, 9};

अपेक्षित आउटपुट:
long long expected = 7;
इनपुट:
long[] numbers = new long[] {4, 9, 7, 9};

अपेक्षित आउटपुट:
long expected = 7;

व्याख्या

Distinct values are 9, 7, 4; the second largest is 7.

उदाहरण 2
इनपुट:
numbers = [5, 5]

अपेक्षित आउटपुट:
expected = -1
इनपुट:
std::vector<long long> numbers = {5, 5};

अपेक्षित आउटपुट:
long long expected = -1;
इनपुट:
long[] numbers = new long[] {5, 5};

अपेक्षित आउटपुट:
long expected = -1;

व्याख्या

Only one distinct value exists, so the answer is -1.

कैसे हल करें

पहले खुद कोशिश करें, फिर एक-एक करके संकेत खोलें।

संकेत 1

You need the largest and the next different value, not just the top two positions.

संकेत 2

Track two distinct maxima as you scan, updating them when a new value fits above or between them.

संकेत 3

If no second distinct value ever appears, return the special fallback value.

अपेक्षित जटिलता

O(n) time, O(1) extra space

संदर्भ

यह चुनौती CodeUtility के लिए अनुकूलित की गई है। ऊपर दिए गए स्टेटमेंट और सीमाओं का पालन करें।

दूसरों से सीखें

समुदाय समाधान

अभी तक कोई प्रकाशित समाधान नहीं। पहला साझा करने के लिए इस चुनौती को हल करें।