question_slug
stringlengths
3
77
title
stringlengths
1
183
slug
stringlengths
12
45
summary
stringlengths
1
160
author
stringlengths
2
30
certification
stringclasses
2 values
created_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
updated_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
hit_count
int64
0
10.6M
has_video
bool
2 classes
content
stringlengths
4
576k
upvotes
int64
0
11.5k
downvotes
int64
0
358
tags
stringlengths
2
193
comments
int64
0
2.56k
fizz-buzz-multithreaded
C++ atomic
c-atomic-by-wiryls-8nx2
Use one atomic<int> as a counter.\n\nc++\nstruct FizzBuzz\n{\npublic:\n FizzBuzz(int n)\n : k(1)\n , n(n)\n {}\n\n // printFizz() outputs
wiryls
NORMAL
2019-09-29T03:19:25.528387+00:00
2019-09-29T03:19:25.528436+00:00
399
false
Use one `atomic<int>` as a counter.\n\n```c++\nstruct FizzBuzz\n{\npublic:\n FizzBuzz(int n)\n : k(1)\n , n(n)\n {}\n\n // printFizz() outputs "fizz".\n void fizz(function<void()> output)\n {\n auto outputx = [&](auto i) { output(); };\n output_if(outputx, [](auto i) { return i % 3 == 0 && i % 5 != 0; });\n }\n\n // printBuzz() outputs "buzz".\n void buzz(function<void()> output)\n {\n auto outputx = [&](auto i) { output(); };\n output_if(outputx, [](auto i) { return i % 3 != 0 && i % 5 == 0; });\n }\n\n // printFizzBuzz() outputs "fizzbuzz".\n\tvoid fizzbuzz(function<void()> output)\n {\n auto outputx = [&](auto i) { output(); };\n output_if(outputx, [](auto i) { return i % 3 == 0 && i % 5 == 0; });\n }\n\n // printNumber(x) outputs "x", where x is an integer.\n void number(function<void(int)> outputx)\n {\n output_if(outputx, [](auto i) { return i % 3 != 0 && i % 5 != 0; });\n }\n \n template<typename T, typename U> inline\n void output_if(T print, U condition)\n {\n while (k.load() <= n)\n {\n auto i = k.load();\n if (condition(i))\n {\n print(i);\n k.store(i + 1);\n }\n else\n {\n std::this_thread::yield();\n }\n }\n }\n \nprivate:\n atomic<int> k;\n int n;\n};\n```
2
0
['C']
2
fizz-buzz-multithreaded
[Java] Basic CyclicBarrier solution - 4ms, 36MB
java-basic-cyclicbarrier-solution-4ms-36-m2am
You process one number at a time. When all 4 threads run together at the same time, only one thing (the same number) will be printed due to the unique if-condit
lk00100100
NORMAL
2019-09-22T23:47:22.667313+00:00
2020-07-13T13:50:16.095774+00:00
246
false
You process one number at a time. When all 4 threads run together at the same time, only one thing (the same number) will be printed due to the unique if-conditions. All threads must await() before going to the next number. Once all 4 threads have hit await(), the barrier will open thus starting the "process one number" cycle over again.\n\nThe program runs like this:\nAll 4 threads process the number 1, await for all 4 threads.\nAll 4 threads process the number 2, await for all 4 threads.\n...\nAll 4 threads process the number n, await for all 4 threads.\nDone\n\n```\nclass FizzBuzz {\n int n; //shared stuff needs synchronization. but it\'s not by default so... eh...\n CyclicBarrier waitingForNextNumber;\n\n public FizzBuzz(int n) {\n this.n = n;\n \n //4 parties need to await before going\n waitingForNextNumber = new CyclicBarrier(4); \n }\n\n // printFizz.run() outputs "fizz".\n public void fizz(Runnable printFizz) throws InterruptedException {\n try{ \n for(int i = 1; i <= n; i++){\n if(i % 3 == 0 && i % 5 != 0)\n printFizz.run();\n\n waitingForNextNumber.await();\n }\n }\n catch(BrokenBarrierException ex){\n //do nothing\n }\n }\n\n // printBuzz.run() outputs "buzz".\n public void buzz(Runnable printBuzz) throws InterruptedException {\n try{\n for(int i = 1; i <= n; i++){\n if(i % 3 != 0 && i % 5 == 0)\n printBuzz.run();\n\n waitingForNextNumber.await(); \n }\n }\n catch(BrokenBarrierException ex){\n //do nothing\n }\n }\n\n // printFizzBuzz.run() outputs "fizzbuzz".\n public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n try{\n for(int i = 1; i <= n; i++){\n if(i % 3 == 0 && i % 5 == 0)\n printFizzBuzz.run();\n\n waitingForNextNumber.await();\n }\n }\n catch(BrokenBarrierException ex){\n //do nothing\n }\n }\n\n // printNumber.accept(x) outputs "x", where x is an integer.\n public void number(IntConsumer printNumber) throws InterruptedException { \n try{\n for(int i = 1; i <= n; i++){\n if(i % 3 != 0 && i % 5 != 0)\n printNumber.accept(i);\n\n waitingForNextNumber.await();\n }\n }\n catch(BrokenBarrierException ex){\n //do nothing\n }\n }\n}\n```
2
0
[]
1
fizz-buzz-multithreaded
Python 100% with Event
python-100-with-event-by-ls1229-d8bk
number method control the process, in each thread using cur to record the next value to print, only print while cur<=self.n, if cur%15==0 we need to add 3 or 5
ls1229
NORMAL
2019-09-20T16:00:58.980779+00:00
2019-09-20T16:00:58.980830+00:00
344
false
`number` method control the process, in each thread using `cur` to record the next value to print, only print while `cur<=self.n`, if `cur%15==0` we need to add 3 or 5 to the `cur` because the next print is `15` and will jump over 3 or 5.\n```\nfrom threading import Event\nclass FizzBuzz:\n def __init__(self, n: int):\n self.n = n\n self.e_fizz = Event()\n self.e_buzz = Event()\n self.e_fizzbuzz = Event()\n self.e_number = Event()\n self.e_number.set()\n\n # printFizz() outputs "fizz"\n def fizz(self, printFizz: \'Callable[[], None]\') -> None:\n cur = 3\n while cur<=self.n:\n self.e_fizz.wait()\n self.e_fizz.clear()\n printFizz()\n cur+=3\n if cur%15==0:\n cur+=3\n self.e_number.set()\n \n\n # printBuzz() outputs "buzz"\n def buzz(self, printBuzz: \'Callable[[], None]\') -> None:\n cur = 5\n while cur<=self.n:\n self.e_buzz.wait()\n self.e_buzz.clear()\n printBuzz()\n cur+=5\n if cur%15==0:\n cur+=5\n self.e_number.set()\n \n \n # printFizzBuzz() outputs "fizzbuzz"\n def fizzbuzz(self, printFizzBuzz: \'Callable[[], None]\') -> None:\n cur = 15\n while cur<=self.n:\n self.e_fizzbuzz.wait()\n self.e_fizzbuzz.clear()\n printFizzBuzz()\n cur+=15\n self.e_number.set()\n \n\t\t\n\n # printNumber(x) outputs "x", where x is an integer.\n def number(self, printNumber: \'Callable[[int], None]\') -> None:\n \n for i in range(1,self.n+1):\n \n self.e_number.wait()\n self.e_number.clear()\n if i%3==0 and i%5==0:\n self.e_fizzbuzz.set()\n elif i%3==0:\n self.e_fizz.set()\n elif i%5==0:\n self.e_buzz.set()\n else:\n\n printNumber(i)\n self.e_number.set()\n \n```
2
0
[]
0
fizz-buzz-multithreaded
Semaphores
semaphores-by-cds77-zslz
Intuition\nPracticing semaphores\n\n# Approach\nUsing a similar approach for concurrency problems with Semaphores that I figure out the first called method and
cds77
NORMAL
2024-10-19T08:11:25.423709+00:00
2024-10-19T14:59:24.955212+00:00
64
false
# Intuition\nPracticing semaphores\n\n# Approach\nUsing a similar approach for concurrency problems with Semaphores that I figure out the first called method and block it then based on conditions of the problem I release each lock for a method at a time and then in the released method I block thread - perform whats needed - and then release the caller method lock. Rinse. Repeat\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```csharp []\nusing System;\nusing System.Threading;\n\npublic class FizzBuzz {\n private int n;\n private SemaphoreSlim fizz = new(0);\n private SemaphoreSlim buzz = new(0);\n private SemaphoreSlim fizzbuzz = new(0);\n private SemaphoreSlim number = new(1);\n\n public FizzBuzz(int n) {\n this.n = n;\n }\n\n // printFizz() outputs "fizz".\n public void Fizz(Action printFizz) {\n for (int i = 3; i <= n; i += 3) {\n if (i % 5 != 0) {\n fizz.Wait();\n printFizz();\n number.Release();\n }\n }\n }\n\n // printBuzz() outputs "buzz".\n public void Buzz(Action printBuzz) {\n for (int i = 5; i <= n; i += 5) {\n if (i % 3 != 0) {\n buzz.Wait();\n printBuzz();\n number.Release();\n }\n }\n }\n\n // printFizzBuzz() outputs "fizzbuzz".\n public void Fizzbuzz(Action printFizzBuzz) {\n for (int i = 15; i <= n; i += 15) {\n fizzbuzz.Wait(); \n printFizzBuzz();\n number.Release();\n }\n }\n\n // printNumber(x) outputs "x", where x is an integer.\n public void Number(Action<int> printNumber) {\n for (int i = 1; i <= n; i++) {\n number.Wait();\n if (i % 15 == 0) {\n fizzbuzz.Release();\n } else if (i % 3 == 0) {\n fizz.Release();\n } else if (i % 5 == 0) {\n buzz.Release();\n } else {\n printNumber(i);\n number.Release();\n }\n }\n\n fizz.Release();\n buzz.Release();\n fizzbuzz.Release();\n }\n}\n\n```
1
0
['C#']
0
fizz-buzz-multithreaded
Java - Easy to understand 95%
java-easy-to-understand-95-by-mandyadb1-5cg6
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
mandyadb1
NORMAL
2024-08-14T15:33:17.198749+00:00
2024-08-14T15:33:17.198778+00:00
342
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass FizzBuzz {\n private int n;\n int count;\n public FizzBuzz(int n) {\n this.n = n;\n this.count = 1;\n }\n\n // printFizz.run() outputs "fizz".\n public void fizz(Runnable printFizz) throws InterruptedException {\n synchronized(this){\n while(count <= n){\n if(count % 3 == 0 && count % 5 != 0){\n printFizz.run();\n count++;\n notifyAll();\n }else{\n wait();\n continue;\n }\n }\n }\n }\n\n // printBuzz.run() outputs "buzz".\n public void buzz(Runnable printBuzz) throws InterruptedException {\n synchronized(this){\n while(count <= n){\n if(count % 5 == 0 && count % 3 != 0){\n printBuzz.run();\n count++;\n notifyAll();\n }else{\n wait();\n continue;\n }\n }\n }\n }\n\n // printFizzBuzz.run() outputs "fizzbuzz".\n public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n synchronized(this){\n while(count <= n){\n if(count % 3 == 0 && count % 5 == 0){\n printFizzBuzz.run();\n count++;\n notifyAll();\n }else{\n wait();\n continue;\n }\n }\n }\n }\n\n // printNumber.accept(x) outputs "x", where x is an integer.\n public void number(IntConsumer printNumber) throws InterruptedException {\n synchronized(this){\n while(count <= n){\n if(count % 3 == 0 || count % 5 == 0){\n wait();\n continue;\n }\n printNumber.accept(count);\n count++;\n notifyAll();\n }\n }\n }\n}\n```
1
0
['Java']
0
fizz-buzz-multithreaded
[C++] Mutex for each function. Simple to understand solution.
c-mutex-for-each-function-simple-to-unde-b1x3
Intuition\nEach function has a mutex to prevent unorderly execution. All mutexes are controled via mutexManager() method which tracks the current number and unl
merab_m_
NORMAL
2024-07-27T10:39:40.423939+00:00
2024-07-27T10:39:40.423976+00:00
63
false
# Intuition\nEach function has a mutex to prevent unorderly execution. All mutexes are controled via `mutexManager()` method which tracks the current number and unlocks respective mutex.\n# Code\n```\nclass FizzBuzz {\nprivate:\n int n;\n\n int nextNumber = 1;\n std::mutex mnum, mfizz, mbuzz, mfizzbuzz;\n\npublic:\n FizzBuzz(int n) {\n this->n = n;\n mfizz.lock();\n mbuzz.lock();\n mfizzbuzz.lock();\n }\n\n void manageMutex()\n {\n if(nextNumber > n)\n {\n mfizz.unlock();\n mbuzz.unlock();\n mfizzbuzz.unlock();\n mnum.unlock();\n return;\n }\n\n if(nextNumber % 3 != 0 && nextNumber % 5 != 0)\n mnum.unlock();\n else if (nextNumber % 3 == 0 && nextNumber % 5 == 0)\n mfizzbuzz.unlock();\n else if (nextNumber % 3 == 0)\n mfizz.unlock();\n else\n mbuzz.unlock();\n }\n\n // printFizz() outputs "fizz".\n void fizz(function<void()> printFizz) {\n while(true)\n {\n mfizz.lock();\n if(nextNumber > n)\n break;\n printFizz();\n nextNumber += 1;\n manageMutex();\n }\n }\n\n // printBuzz() outputs "buzz".\n void buzz(function<void()> printBuzz) {\n while(true)\n {\n mbuzz.lock();\n if(nextNumber > n)\n break;\n\n printBuzz();\n nextNumber += 1;\n manageMutex();\n }\n }\n\n // printFizzBuzz() outputs "fizzbuzz".\n\tvoid fizzbuzz(function<void()> printFizzBuzz) {\n while(true)\n {\n mfizzbuzz.lock();\n if(nextNumber > n)\n break;\n printFizzBuzz();\n nextNumber += 1;\n manageMutex();\n }\n }\n\n // printNumber(x) outputs "x", where x is an integer.\n void number(function<void(int)> printNumber) {\n while(true)\n {\n mnum.lock();\n if(nextNumber > n)\n break;\n printNumber(nextNumber);\n nextNumber += 1;\n manageMutex();\n }\n }\n};\n```
1
0
['C++']
0
fizz-buzz-multithreaded
Beats 97% Java Users......
beats-97-java-users-by-aim_high_212-d53r
\n\n# Code\n\nimport java.util.ConcurrentModificationException;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.IntConsumer;\n\ncl
Aim_High_212
NORMAL
2024-03-31T08:23:05.546155+00:00
2024-03-31T08:23:05.546185+00:00
127
false
\n\n# Code\n```\nimport java.util.ConcurrentModificationException;\nimport java.util.concurrent.atomic.AtomicInteger;\nimport java.util.function.IntConsumer;\n\nclass FizzBuzz {\n\n private final AtomicInteger counter;\n\n private final int n;\n\n public FizzBuzz(int n) {\n this.n = n;\n counter = new AtomicInteger(1);\n }\n\n private void updateToNext(int count) {\n if (!counter.compareAndSet(count, count + 1))\n throw new ConcurrentModificationException();\n }\n\n public void fizz(Runnable printFizz) throws InterruptedException {\n int count;\n while ((count = counter.get()) <= n) {\n if (count % 3 == 0 && count % 5 != 0) {\n printFizz.run();\n updateToNext(count);\n }\n }\n }\n\n public void buzz(Runnable printBuzz) throws InterruptedException {\n int count;\n while ((count = counter.get()) <= n) {\n if (count % 3 != 0 && count % 5 == 0) {\n printBuzz.run();\n updateToNext(count);\n }\n }\n }\n\n public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n int count;\n while ((count = counter.get()) <= n) {\n if (count % 3 == 0 && count % 5 == 0) {\n printFizzBuzz.run();\n updateToNext(count);\n }\n }\n }\n\n public void number(IntConsumer printNumber) throws InterruptedException {\n int count;\n while ((count = counter.get()) <= n) {\n if (count % 3 != 0 && count % 5 != 0) {\n printNumber.accept(count);\n updateToNext(count);\n }\n }\n }\n}\n```
1
0
['Java']
10
fizz-buzz-multithreaded
std:: Conditional Variable Solution
std-conditional-variable-solution-by-ank-cz3w
\n\n# Code\n\nclass FizzBuzz {\nprivate:\n int n;\n mutex m;\n condition_variable c;\n int i;\n\npublic:\n FizzBuzz(int n) {\n \n t
ankush20386
NORMAL
2024-03-16T06:37:28.353823+00:00
2024-03-16T06:37:28.353850+00:00
620
false
\n\n# Code\n```\nclass FizzBuzz {\nprivate:\n int n;\n mutex m;\n condition_variable c;\n int i;\n\npublic:\n FizzBuzz(int n) {\n \n this->n = n;\n this->i=1;\n }\n\n // printFizz() outputs "fizz".\n void fizz(function<void()> printFizz) {\n while(i<=n)\n {\n unique_lock<mutex>lock(m);\n while(i<=n && (((i%3)==0) && ((i%5)!=0))==0){\n c.wait(lock);\n }\n if(i<=n){\n printFizz();\n ++i;\n }\n c.notify_all();\n }\n \n }\n\n // printBuzz() outputs "buzz".\n void buzz(function<void()> printBuzz) {\n while(i<=n)\n {\n unique_lock<mutex>lock(m);\n while(i<=n && (((i%5)==0) && ((i%3)!=0))==0){\n c.wait(lock);\n }\n if(i<=n){\n printBuzz();\n ++i;\n }\n c.notify_all();\n }\n }\n\n // printFizzBuzz() outputs "fizzbuzz".\n\tvoid fizzbuzz(function<void()> printFizzBuzz) {\n while(i<=n)\n {\n unique_lock<mutex>lock(m);\n while(i<=n && (((i%5)==0) && ((i%3)==0))==0){\n c.wait(lock);\n }\n if(i<=n){\n printFizzBuzz();\n ++i;\n }\n c.notify_all();\n }\n }\n\n // printNumber(x) outputs "x", where x is an integer.\n void number(function<void(int)> printNumber) {\n while(i<=n)\n {\n unique_lock<mutex>lock(m);\n while(i<=n && (((i%5)!=0) && ((i%3)!=0))==0){\n c.wait(lock);\n }\n if(i<=n){\n printNumber(i++);\n \n }\n c.notify_all();\n }\n }\n};\n```
1
0
['C++']
2
fizz-buzz-multithreaded
Clean solution with threading.Condition in 22 ms
clean-solution-with-threadingcondition-i-ddo9
Approach\nIf semaphore (or threading.Event) are used to achieve synchornizaiton, 4 semaphores (or threading.Event) will be needed. 1 condistion variable and not
weii666
NORMAL
2024-02-24T14:22:52.443649+00:00
2024-02-24T14:25:53.105697+00:00
175
false
# Approach\nIf semaphore (or threading.Event) are used to achieve synchornizaiton, 4 semaphores (or threading.Event) will be needed. 1 condistion variable and notifyAll() are the right mechnisms in this scenario:\n\n- 1 counter, `self.ctr`, is shared by 4 threads\n- for any value of `self.ctr`, there is exactly one thread to run\n- each thread does not know which thread is to run next\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass FizzBuzz:\n def __init__(self, n: int):\n self.n = n\n self.ctr = 1\n self.cond = threading.Condition()\n\n # printFizz() outputs "fizz"\n def fizz(self, printFizz: \'Callable[[], None]\') -> None:\n \twith self.cond: \n while self.ctr <= self.n: \n if self.ctr % 3 == 0 and self.ctr % 5 != 0:\n printFizz()\n self.ctr += 1\n self.cond.notifyAll()\n else:\n self.cond.wait()\n\n # printBuzz() outputs "buzz"\n def buzz(self, printBuzz: \'Callable[[], None]\') -> None:\n \twith self.cond: \n while self.ctr <= self.n:\n if self.ctr % 3 != 0 and self.ctr % 5 == 0:\n printBuzz()\n self.ctr += 1\n self.cond.notifyAll()\n else:\n self.cond.wait()\n\n # printFizzBuzz() outputs "fizzbuzz"\n def fizzbuzz(self, printFizzBuzz: \'Callable[[], None]\') -> None:\n with self.cond: \n while self.ctr <= self.n:\n if self.ctr % 3 == 0 and self.ctr % 5 == 0:\n printFizzBuzz()\n self.ctr += 1\n self.cond.notifyAll()\n else:\n self.cond.wait()\n\n # printNumber(x) outputs "x", where x is an integer.\n def number(self, printNumber: \'Callable[[int], None]\') -> None:\n with self.cond:\n while self.ctr <= self.n:\n if self.ctr % 3 != 0 and self.ctr % 5 != 0:\n printNumber(self.ctr)\n self.ctr += 1\n self.cond.notifyAll()\n else:\n self.cond.wait()\n```
1
0
['Python3']
0
fizz-buzz-multithreaded
Simple solution using wait() and notifyAll()
simple-solution-using-wait-and-notifyall-o53f
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
vipin_sharma
NORMAL
2024-02-07T07:25:49.184085+00:00
2024-02-07T07:25:49.184111+00:00
203
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass FizzBuzz {\n private int n;\n private int i = 1;\n\n public FizzBuzz(int n) {\n this.n = n;\n }\n\n // printFizz.run() outputs "fizz".\n public synchronized void fizz(Runnable printFizz) throws InterruptedException {\n while(i <= n) {\n if(i%3==0&&i%5!=0) {\n printFizz.run();\n i++;\n notifyAll();\n }\n else {\n wait();\n }\n }\n }\n\n // printBuzz.run() outputs "buzz".\n public synchronized void buzz(Runnable printBuzz) throws InterruptedException {\n while(i <= n) {\n if(i%5==0 && i%3!=0) {\n printBuzz.run();\n i++;\n notifyAll();\n }\n else {\n wait();\n }\n }\n }\n\n // printFizzBuzz.run() outputs "fizzbuzz".\n public synchronized void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {\n while(i <= n) {\n if(i%15==0) {\n printFizzBuzz.run();\n i++;\n notifyAll();\n }\n else {\n wait();\n }\n }\n }\n\n // printNumber.accept(x) outputs "x", where x is an integer.\n public synchronized void number(IntConsumer printNumber) throws InterruptedException {\n while(i <= n) {\n if(i%3!=0&&i%5!=0) {\n printNumber.accept(i);\n i++;\n notifyAll();\n }\n else {\n wait();\n }\n }\n }\n}\n```
1
0
['Java']
0
fizz-buzz-multithreaded
Multithreading w/ spinlocks avoiding mutex/monitor locks; async calculations
multithreading-w-spinlocks-avoiding-mute-8g1g
Code\n\npublic class FizzBuzz\n{\n\n private int _printerIndex = 1;\n private readonly int _n;\n\n public FizzBuzz(int n) {\n _n = n;\n }\n\n
salma2vec
NORMAL
2023-11-11T09:36:32.361925+00:00
2023-11-11T09:36:32.361944+00:00
196
false
# Code\n```\npublic class FizzBuzz\n{\n\n private int _printerIndex = 1;\n private readonly int _n;\n\n public FizzBuzz(int n) {\n _n = n;\n }\n\n private void WaitForPrinterIndexAndIncrement(int i, Action action)\n {\n if (_printerIndex < i)\n System.Threading.SpinWait.SpinUntil(() => _printerIndex == i);\n\n action();\n _printerIndex += 1;\n }\n\n public void Fizz(Action printFizz)\n {\n for (var i = 1; i <= _n; i++)\n {\n if (i % 3 == 0 && i % 5 != 0)\n WaitForPrinterIndexAndIncrement(i, printFizz);\n }\n }\n\n public void Buzz(Action printBuzz)\n {\n for (var i = 1; i <= _n; i++)\n {\n if (i % 3 != 0 && i % 5 == 0)\n WaitForPrinterIndexAndIncrement(i, printBuzz);\n }\n }\n\n public void Fizzbuzz(Action printFizzBuzz) \n {\n for (var i = 1; i <= _n; i++)\n {\n if (i % 15 == 0)\n WaitForPrinterIndexAndIncrement(i, printFizzBuzz);\n }\n }\n\n public void Number(Action<int> printNumber) \n {\n for (var i = 1; i <= _n; i++)\n {\n var iCopy = i; \n if (i % 3 != 0 && i % 5 != 0)\n WaitForPrinterIndexAndIncrement(i, () => printNumber(iCopy));\n }\n }\n}\n```
1
0
['Concurrency', 'C#']
0
fizz-buzz-multithreaded
Python very simple solution with semaphores
python-very-simple-solution-with-semapho-bhx6
Intuition\n Describe your first thoughts on how to solve this problem. \nEach function has its own counter which is incremented by either 1, 3, 5, or 15.\n\nIn
sstef
NORMAL
2023-10-18T15:16:07.594608+00:00
2023-10-18T15:16:07.594633+00:00
347
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nEach function has its own counter which is incremented by either 1, 3, 5, or 15.\n\nIn fizz and buzz methods if after increment we get number divisible by both 3 and 5 just increment once again.\n\n# Code\n```\nfrom threading import Semaphore\n\nclass FizzBuzz:\n def __init__(self, n: int):\n self.n = n\n\n self.fizzSem = Semaphore(0)\n self.buzzSem = Semaphore(0)\n self.fizzBuzzSem = Semaphore(0)\n self.mainSem = Semaphore(1)\n\n def fizz(self, printFizz: \'Callable[[], None]\') -> None:\n i = 3\n while i <= self.n:\n self.fizzSem.acquire()\n printFizz()\n self.mainSem.release()\n i += 3\n if i % 5 == 0:\n i += 3\n\n def buzz(self, printBuzz: \'Callable[[], None]\') -> None:\n i = 5\n while i <= self.n:\n self.buzzSem.acquire()\n printBuzz()\n self.mainSem.release()\n i += 5\n if i % 3 == 0:\n i += 5\n\n def fizzbuzz(self, printFizzBuzz: \'Callable[[], None]\') -> None:\n i = 15\n while i <= self.n:\n self.fizzBuzzSem.acquire()\n printFizzBuzz()\n self.mainSem.release()\n i += 15\n \n\n def number(self, printNumber: \'Callable[[int], None]\') -> None:\n\n for i in range(1, self.n + 1):\n self.mainSem.acquire()\n if i % 3 == 0 and i % 5 == 0:\n self.fizzBuzzSem.release()\n elif i % 3 == 0:\n self.fizzSem.release()\n elif i % 5 == 0:\n self.buzzSem.release()\n else:\n printNumber(i)\n self.mainSem.release()\n \n```
1
0
['Python3']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
✅Easiest 4 Step Cpp / Java / Py / JS Solution | Normal Approach🏆| With Explanation
easiest-4-step-cpp-java-py-js-solution-n-l2yh
🌟 Step-by-Step Breakdown 🌟1. 🚶 Traverse the Linked List: Identify critical points (either local minima or maxima). Use pointers (prev, curr, and next) to compar
dev_yash_
NORMAL
2024-07-05T00:48:14.553328+00:00
2024-12-17T16:33:18.853846+00:00
22,124
false
### \uD83C\uDF1F **Step-by-Step Breakdown** \uD83C\uDF1F \n\n**1. \uD83D\uDEB6 Traverse the Linked List:** \nIdentify critical points (either local minima or maxima). \n- Use pointers (`prev`, `curr`, and `next`) to compare the current node\u2019s value with its neighbors. \n- Critical Point: \n - **Peak:** `curr.val > prev.val && curr.val > next.val` \n - **Valley:** `curr.val < prev.val && curr.val < next.val` \n\n---\n\n**2. \uD83D\uDCDD Record Positions of Critical Points:** \nStore the indices of critical points in a list for later calculations. \n- If no critical points or just one, skip the distance calculations.\n\n---\n\n**3. \uD83D\uDCCF Calculate Distances:** \n- **Minimum Distance:** Find the smallest gap between consecutive critical points. \n- **Maximum Distance:** Compute the distance between the first and last critical points. \n- Return `[-1, -1]` if fewer than two critical points are found.\n\n---\n\n**\uD83C\uDFAF Return the Results:** \n- If critical points exist: return `[minDistance, maxDistance]`. \n- Otherwise: return `[-1, -1]`. \n\n---\n\n\n\n### \uD83D\uDCBB C++\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\n\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n vector<int> criticalPts;\n ListNode* prev = nullptr;\n ListNode* curr = head;\n int pos = 0;\n while (curr->next != nullptr) {\n // 1.Traverse and find points\n if (prev != nullptr) {\n // 2.check local min and max and record position\n if ((curr->val > prev->val && curr->val > curr->next->val) ||\n (curr->val < prev->val && curr->val < curr->next->val)) {\n criticalPts.push_back(pos);\n }\n }\n prev = curr;\n curr = curr->next;\n pos++;\n }\n if (criticalPts.size() < 2) {\n return {-1, -1};\n }\n\n // 3. Calculate Distances\n int minDist = INT_MAX;\n int maxDist = criticalPts.back() - criticalPts.front();\n for (int i = 1; i < criticalPts.size(); i++) {\n minDist = min(minDist, criticalPts[i] - criticalPts[i - 1]);\n }\n\n // return ans\n return {minDist, maxDist};\n }\n};\n\n```\n### Java\n```\nclass Solution {\n public int[] nodesBetweenCriticalPoints(ListNode head) {\n if (head == null || head.next == null || head.next.next == null) {\n return new int[]{-1, -1};\n }\n\n List<Integer> criticalPts = new ArrayList<>();\n ListNode prev = null;\n ListNode curr = head;\n int pos = 0;\n\n while (curr != null && curr.next != null) {\n // 1. Traverse and find points\n if (prev != null) {\n // 2. Check local min and max and record position\n if ((curr.val > prev.val && curr.val > curr.next.val) ||\n (curr.val < prev.val && curr.val < curr.next.val)) {\n criticalPts.add(pos);\n }\n }\n prev = curr;\n curr = curr.next;\n pos++;\n }\n\n if (criticalPts.size() < 2) {\n return new int[]{-1, -1};\n }\n\n // 3. Calculate Distances\n int minDist = Integer.MAX_VALUE;\n int maxDist = criticalPts.get(criticalPts.size() - 1) - criticalPts.get(0);\n\n for (int i = 1; i < criticalPts.size(); i++) {\n minDist = Math.min(minDist, criticalPts.get(i) - criticalPts.get(i - 1));\n }\n\n // return ans\n return new int[]{minDist, maxDist};\n }\n}\n```\n\n### Python3\n```\nclass Solution:\n def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:\n if not head or not head.next or not head.next.next:\n return [-1, -1]\n\n criticalPts = [] \n prev = head\n curr = head.next\n pos = 1 \n\n while curr.next:\n # 1. Traverse and find points\n if (curr.val > prev.val and curr.val > curr.next.val) or (curr.val < prev.val and curr.val < curr.next.val):\n criticalPts.append(pos) # Record position of critical points\n prev = curr\n curr = curr.next\n pos += 1 \n\n if len(criticalPts) < 2:\n return [-1, -1]\n\n # 2. Calculate Distances\n minDist = float(\'inf\')\n maxDist = criticalPts[-1] - criticalPts[0]\n\n for i in range(1, len(criticalPts)):\n minDist = min(minDist, criticalPts[i] - criticalPts[i - 1]) # Find the minimum distance\n\n # Return the result\n return [minDist, maxDist]\n\n```\n### JavaScript\n```\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val === undefined ? 0 : val);\n * this.next = (next === undefined ? null : next);\n * }\n */\n/**\n * @param {ListNode} head\n * @return {number[]}\n */\nvar nodesBetweenCriticalPoints = function(head) {\n if (!head || !head.next || !head.next.next) {\n return [-1, -1];\n }\n\n const criticalPts = []; \n let prev = head;\n let curr = head.next;\n let pos = 1; \n\n while (curr.next) {\n // 1. Traverse and find points\n if ((curr.val > prev.val && curr.val > curr.next.val) || (curr.val < prev.val && curr.val < curr.next.val)) {\n criticalPts.push(pos); // Record position of critical points\n }\n prev = curr;\n curr = curr.next;\n pos++; \n }\n\n if (criticalPts.length < 2) {\n return [-1, -1];\n }\n\n // 2. Calculate Distances\n let minDist = Infinity;\n let maxDist = criticalPts[criticalPts.length - 1] - criticalPts[0];\n\n for (let i = 1; i < criticalPts.length; i++) {\n minDist = Math.min(minDist, criticalPts[i] - criticalPts[i - 1]); // Find the minimum distance\n }\n\n // Return the result\n return [minDist, maxDist];\n};\n\n\n```\n#### STAY COOL STAY DISCIPLINED..\n\n![image](https://assets.leetcode.com/users/images/ad294515-01e3-4704-a668-9bcc5b0e822c_1717851160.1975598.gif)
94
6
['Linked List', 'C', 'Python', 'C++', 'Java', 'Python3', 'JavaScript']
15
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
One Pass
one-pass-by-votrubac-7pce
To make it simple, we track:\n- first and last indexes of local min/max.\n- the value of the previous node prev_val.\n- smallest difference between two adjacent
votrubac
NORMAL
2021-10-31T04:02:07.587764+00:00
2021-10-31T04:51:28.218354+00:00
8,336
false
To make it simple, we track:\n- `first` and `last` indexes of local min/max.\n- the value of the previous node `prev_val`.\n- smallest difference between two adjacent indices (current `i` minus `last`) as `min_d`.\n\nThe result is `{min_d, last - first}`.\n\nThe complexity of this solution is *O(n)* time and *O(1)* memory.\n\n**C++**\n```cpp\nvector<int> nodesBetweenCriticalPoints(ListNode* h) {\n int first = INT_MAX, last = 0, prev_val = h->val, min_d = INT_MAX;\n for (int i = 0; h->next != nullptr; ++i) {\n if ((max(prev_val, h->next->val) < h->val) || \n (min(prev_val, h->next->val) > h->val)) {\n if (last != 0)\n min_d = min(min_d, i - last);\n first = min(first, i);\n last = i;\n }\n prev_val = h->val;\n h = h->next;\n }\n if (min_d == INT_MAX)\n return {-1, -1};\n return {min_d, last - first};\n}\n```\n**Java**\n```java\npublic int[] nodesBetweenCriticalPoints(ListNode h) {\n int first = Integer.MAX_VALUE, last = 0, prev_val = h.val, min_d = Integer.MAX_VALUE;\n for (int i = 0; h.next != null; ++i) {\n if ((prev_val < h.val && h.val > h.next.val) || \n (prev_val > h.val && h.val < h.next.val)) {\n if (last != 0)\n min_d = Math.min(min_d, i - last);\n first = Math.min(first, i);\n last = i;\n }\n prev_val = h.val;\n h = h.next;\n } \n if (min_d == Integer.MAX_VALUE)\n return new int[] {-1, -1};\n return new int[] {min_d, last - first};\n}\n```
74
3
['C', 'Java']
15
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
[LinkedList Tutorial] Find the Minimum and Maximum Number of Nodes Between Critical Points
linkedlist-tutorial-find-the-minimum-and-p24y
Topic : Linked List\nA linked list is a fundamental data structure in computer science. It consists of nodes where each node contains data and a reference (lin
never_get_piped
NORMAL
2024-07-05T00:26:15.671080+00:00
2024-07-05T05:30:32.192582+00:00
9,479
false
**Topic** : Linked List\nA linked list is a fundamental data structure in computer science. It consists of nodes where each node contains data and a reference (link) to the next node in the sequence. This allows for dynamic memory allocation and efficient insertion and deletion operations compared to arrays. (GFG)\n\nThe crucial aspect to note about linked list:\n* For adding a new node or deleting an existing node, the operations in a linked list are `O(1)`.\n* To traverse the entire list, the time complexity in a linked list is `O(n)`.\n* It can also serve as a stack or a queue.\n\n___\n\n## Solution\nTo traverse a linked list, we can employ the following straightforward pseudocode:\n```\nwhile(node != null) {\n\tprint(node);\n\tnode = node.next;\n}\n```\n\nTo identify a node as a critical point, we require information about both its preceding and succeeding nodes. While traversing our linked list, it\'s essential to keep track of the previous node. We maintain the following information using the pseudocode:\n```\npreNode = null;\ncurNode = head;\nwhile(curNode != null) {\n\tprint(node);\n\tpreNode = node;\n\tcurNode = curNode.next;\n}\n```\n\nAfter determining whether a node is critical or not, to find the maximum and minimum distances: **the maximum distance spans from the first to the last critical node, while the minimum distance occurs between any two adjacent critical nodes**.\n\nSo, we need to maintain the positions of the following critical nodes: the first critical node encountered, the current critical node position, and the position of the previous critical node.\n\n<br/>\n\n```c++ []\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n ListNode* pre = head; \n ListNode*cur = head -> next;\n vector<int> ans = {-1, -1};\n int prePosition = -1, curPosition = -1, firstPosition = -1, position = 0;\n while(cur -> next != NULL) {\n if((cur -> val < pre -> val && cur -> val < cur -> next -> val) || (cur -> val > pre -> val && cur -> val > cur -> next -> val)) {\n //local\n prePosition = curPosition;\n curPosition = position;\n if(firstPosition == -1) {\n firstPosition = position;\n }\n if(prePosition != -1) {\n if(ans[0] == -1) ans[0] = curPosition - prePosition;\n else ans[0] = min(ans[0], curPosition - prePosition);\n ans[1] = position - firstPosition;\n }\n }\n position++;\n pre = cur;\n cur = cur -> next;\n }\n return ans;\n }\n};\n```\n```java []\nclass Solution {\n public int[] nodesBetweenCriticalPoints(ListNode head) {\n ListNode pre = head;\n ListNode cur = head.next;\n int[] ans = {-1, -1};\n int prePosition = -1, curPosition = -1, firstPosition = -1, position = 0;\n while (cur.next != null) {\n if ((cur.val < pre.val && cur.val < cur.next.val) || (cur.val > pre.val && cur.val > cur.next.val)) {\n // local\n prePosition = curPosition;\n curPosition = position;\n if (firstPosition == -1) {\n firstPosition = position;\n }\n if (prePosition != -1) {\n if (ans[0] == -1) ans[0] = curPosition - prePosition;\n else ans[0] = Math.min(ans[0], curPosition - prePosition);\n ans[1] = position - firstPosition;\n }\n }\n position++;\n pre = cur;\n cur = cur.next;\n }\n return ans;\n }\n}\n```\n```python []\nclass Solution:\n def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:\n pre = head\n cur = head.next\n ans = [-1, -1]\n prePosition, curPosition,firstPosition, position = -1, -1, -1, 0\n\n while cur.next is not None:\n if (cur.val < pre.val and cur.val < cur.next.val) or (cur.val > pre.val and cur.val > cur.next.val):\n # local\n prePosition = curPosition\n curPosition = position\n \n if firstPosition == -1:\n firstPosition = position\n if prePosition != -1:\n if ans[0] == -1:\n ans[0] = curPosition - prePosition\n else:\n ans[0] = min(ans[0], curPosition - prePosition)\n ans[1] = position - firstPosition\n position += 1\n pre = cur\n cur = cur.next\n return ans\n```\n```Go []\n/**\n * Definition for singly-linked list.\n * type ListNode struct {\n * Val int\n * Next *ListNode\n * }\n */\nfunc nodesBetweenCriticalPoints(head *ListNode) []int {\n pre := head\n cur := head.Next\n ans := []int{-1, -1}\n prePosition, curPosition, firstPosition, position := -1, -1, -1, 0\n \n for cur.Next != nil {\n if (cur.Val < pre.Val && cur.Val < cur.Next.Val) || (cur.Val > pre.Val && cur.Val > cur.Next.Val) {\n // local\n prePosition = curPosition\n curPosition = position\n \n if firstPosition == -1 {\n firstPosition = position\n }\n if prePosition != -1 {\n if ans[0] == -1 {\n ans[0] = curPosition - prePosition\n } else {\n if curPosition-prePosition < ans[0] {\n ans[0] = curPosition - prePosition\n }\n }\n ans[1] = position - firstPosition\n }\n }\n position++\n pre = cur\n cur = cur.Next\n }\n return ans\n}\n```\n```PHP []\nclass Solution {\n\n /**\n * @param ListNode $head\n * @return Integer[]\n */\n function nodesBetweenCriticalPoints($head) {\n $pre = $head;\n $cur = $head->next;\n $ans = [-1, -1];\n $prePosition = -1;\n $curPosition = -1;\n $firstPosition = -1;\n $position = 0;\n \n while ($cur->next != null) {\n if (($cur->val < $pre->val && $cur->val < $cur->next->val) || ($cur->val > $pre->val && $cur->val > $cur->next->val)) {\n // local\n $prePosition = $curPosition;\n $curPosition = $position;\n \n if ($firstPosition == -1) {\n $firstPosition = $position;\n }\n if ($prePosition != -1) {\n if ($ans[0] == -1) {\n $ans[0] = $curPosition - $prePosition;\n } else {\n $ans[0] = min($ans[0], $curPosition - $prePosition);\n }\n $ans[1] = $position - $firstPosition;\n }\n }\n $position++;\n $pre = $cur;\n $cur = $cur->next;\n }\n return $ans;\n }\n}\n```\n```javascript []\nvar nodesBetweenCriticalPoints = function(head) {\n let pre = head;\n let cur = head.next;\n let ans = [-1, -1];\n let prePosition = -1, curPosition = -1, firstPosition = -1, position = 0;\n \n while (cur.next !== null) {\n if ((cur.val < pre.val && cur.val < cur.next.val) || (cur.val > pre.val && cur.val > cur.next.val)) {\n // local\n prePosition = curPosition;\n curPosition = position;\n \n if (firstPosition === -1) {\n firstPosition = position;\n }\n \n if (prePosition !== -1) {\n if (ans[0] === -1) {\n ans[0] = curPosition - prePosition;\n } else {\n ans[0] = Math.min(ans[0], curPosition - prePosition);\n }\n \n ans[1] = position - firstPosition;\n }\n }\n position++;\n pre = cur;\n cur = cur.next;\n }\n \n return ans; \n};\n```\n\n**Complexity**:\n* Time Complexity : `O(n)`\n* Space Complexity : `O(1)`\n\n\n**Feel free to leave a comment if something is confusing, or if you have any suggestions on how I can improve the post.**
56
4
['PHP', 'Python', 'Java', 'Go', 'JavaScript']
11
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Loop & Linked list||109ms Beats 99.27%
loop-linked-list109ms-beats-9927-by-anwe-oo6r
Intuition\n Describe your first thoughts on how to solve this problem. \nLinked list & find the locations of critical points.\nThen compute min(pos) & max(pos)\
anwendeng
NORMAL
2024-07-05T01:41:32.077736+00:00
2024-07-05T03:53:58.741172+00:00
5,407
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nLinked list & find the locations of critical points.\nThen compute min(pos) & max(pos)\n\n2nd approach is a 1 pass with O(1) space.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Create an array `pos` for holding the positions for critical points\n2. Consider the comparisons `less` , `bigger `for previous node & the current node & the value `x` for the next node in the linked list through the following loop iteration\n```\nint x=Next->val;\nbool bigger1=x>x1, less1=x<x1;\nif((less && bigger1)||(bigger && less1)){\n pos.push_back(i);\n}\nbigger=bigger1;\nless=less1;\nx1=x;\n```\n3. If `|pos|<=1` return` {-1, -1}`\n4. Otherwise compute `maxD=pos.back()-pos[0]` & `minD=min(pos[i+1]-pos[i] for i=0...sz-2)`. A minor variant using std::adjacent_difference is also presented.\n5. 2nd approach is just a space optimization for the 1st version. Instead of using a container `pos`, variables `p0, p` are in use with some extra if-branches ( which might slow down the speed)\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(|pos|)\\to O(1)$$\n# Code||C++ 109ms Beats 99.27%\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n static vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n vector<int> pos;\n int i=1;\n int x0=head->val, x1=head->next->val;\n bool less=x1<x0, bigger=x1>x0;\n for(ListNode* Next=head->next->next; Next; i++, Next=Next->next){\n int x=Next->val;\n bool bigger1=x>x1, less1=x<x1;\n if((less && bigger1)||(bigger && less1)){\n pos.push_back(i);\n // cout<<i<<",";\n }\n bigger=bigger1;\n less=less1;\n x1=x;\n }\n int sz=pos.size();\n if (sz<=1) return {-1, -1};\n else{\n int maxD=pos.back()-pos[0];\n int minD=INT_MAX;\n for(int i=0; i<sz-1; i++)\n minD=min(minD, pos[i+1]-pos[i]);\n return {minD, maxD};\n }\n }\n};\n\n\n\n\nauto init = []() {\n ios::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n return \'c\';\n}();\n```\n# C++ Minor variant using adjacent_difference computing minD in the last block\n```\n else{\n int maxD=pos.back()-pos[0];\n adjacent_difference(pos.begin(), pos.end(), pos.begin());\n int minD=*min_element(pos.begin()+1, pos.end());\n return {minD, maxD};\n }\n```\n# 1 pass with O(1) space||C++ 120ms Beats 98.39%\n```C++ []\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n static vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n int i=1, sz=0, p0=-1, p=-1, minD=INT_MAX;\n int x0=head->val, x1=head->next->val;\n bool less=x1<x0, bigger=x1>x0;\n for(ListNode* Next=head->next->next; Next; i++, Next=Next->next){\n int x=Next->val;\n bool bigger1=x>x1, less1=x<x1;\n if((less && bigger1)||(bigger && less1)){\n if (sz==0) p0=i;\n sz++;\n if (p!=-1) minD=min(i-p, minD);\n p=i;\n }\n bigger=bigger1;\n less=less1;\n x1=x;\n }\n if (sz<=1) return {-1, -1};\n else return {minD, p-p0};\n }\n};\n\n\n\n\nauto init = []() {\n ios::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n return \'c\';\n}();\n```\n```Python []\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:\n i, sz, p0, p, minD= 1, 0, -1, -1, 2**31\n x0, x1= head.val, head.next.val\n less, bigger= x1<x0, x1>x0\n Next=head.next.next\n while Next:\n x=Next.val\n bigger1, less1=x>x1, x<x1\n if (less and bigger1) or (bigger and less1):\n if sz==0: p0=i\n sz+=1\n if p!=-1: minD=min(minD, i-p)\n p=i\n bigger, less=bigger1, less1\n x1=x\n i+=1\n Next=Next.next\n if sz<=1: return [-1,-1]\n else: return [minD, p-p0]\n \n```
48
3
['Linked List', 'C++', 'Python3']
9
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
✅💯🔥Explanations No One Will Give You🎓🧠Detailed Approach🎯🔥Extremely Simple And Effective🔥
explanations-no-one-will-give-youdetaile-axej
\n \n \n If you don\'t like the road you\'re walking, start paving another one\n \n \n \n
heir-of-god
NORMAL
2024-07-05T06:25:58.354367+00:00
2024-07-05T09:12:31.731898+00:00
4,392
false
<blockquote>\n <p>\n <b>\n If you don\'t like the road you\'re walking, start paving another one\n </b> \n </p>\n <p>\n --- Dolly Parton ---\n </p>\n</blockquote>\n\n# \uD83D\uDC51Problem Explanation and Understanding:\n\n## \uD83C\uDFAF Problem Description\nYou are given a head of the linked list ```head```. You want to calculate minimum and maximum distance (number of edges) between to critical points. Where critical point is defined as node which satisfies this condition: ```node.val > prev_node.val and node.val > node.next.val OR node.val < prev_nove.val and node.val < node.next.val```.\n**Critical point must have both neighbors and if there\'re less than 2 critical points we want to return [-1, -1]**\n\n## \uD83D\uDCE5\u2935\uFE0F Input:\n- Head of the linked list ```head```\n\n## \uD83D\uDCE4\u2934\uFE0F Output:\n1d array of two elements where first element is minimum distance and the second one is maximum distance (or [-1, -1] if there\'re not enough critical points)\n---\n\n# 1\uFE0F\u20E3\uD83C\uDFC6 Approach: One Pass With Index Memorizing\n\n# \uD83E\uDD14 Intuition\n- First, let\'s think about how we can calculate the distance between two list nodes. Everything is very simple - as we go through the list, we will also save the \u201Cindex\u201D or \u201Cnumber\u201D of the node that we are currently looking at from the beginning. Let\'s say, conditionally, that the first node has index 0.\n- Between which critical points will the distance be greatest? The answer is between the one we meet first and the one we meet last.\n- Between which nodes will the distance be the smallest? We can\u2019t say this for sure, but let\u2019s save the index of the previous node every time we meet a critical point and use this to find the minimum distance from past results and from this one.\n- In general, this is all the logic needed for this task, let\'s look at the code.\n\n# \uD83D\uDC69\uD83C\uDFFB\u200D\uD83D\uDCBB Coding \n- Initialize `res` list with `[-1, -1]` to store minimum and maximum distances between critical points.\n- Initialize `prev_critical_ind` and `first_critical_ind` to `None` to track indices of critical points.\n- Set `prev` to the head of the linked list, `cur` to the second node (constraints guarantee that this node exists), and `cur_ind` to 1 to start tracking indices.\n- Loop through the linked list while `cur.next` exists:\n - Check if `cur` is a critical point (local minima or maxima).\n - If `prev_critical_ind` is not `None`, update the minimum distance (`res[0]`).\n - If it\'s the first critical point, set `first_critical_ind`.\n - Update `prev_critical_ind` to the current index.\n- Move `prev` to `cur`, `cur` to `cur.next`, and increment `cur_ind`.\n- After the loop, if there are multiple critical points, update the maximum distance (`res[1]`).\n- Return `res`.\n\n# \uD83D\uDCDA Complexity Analysis\n- \u23F0 Time complexity: O(n), since we visit each node of the linked list once\n- \uD83E\uDDFA Space complexity: O(1), since no extra space is used\n\n# \uD83D\uDCBB Code\n``` python []\nclass Solution:\n def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:\n res = [-1, -1]\n prev_critical_ind = None\n first_critical_ind = None\n prev = head\n cur = head.next\n cur_ind = 1\n\n while cur.next:\n if (cur.val > prev.val and cur.val > cur.next.val) or (cur.val < prev.val and cur.val < cur.next.val):\n print(cur_ind)\n if prev_critical_ind is not None:\n res[0] = min(res[0], cur_ind - prev_critical_ind) if res[0] != -1 else cur_ind - prev_critical_ind\n else: \n first_critical_ind = cur_ind\n prev_critical_ind = cur_ind\n\n prev = cur\n cur = cur.next\n cur_ind += 1\n\n if prev_critical_ind != first_critical_ind:\n res[1] = prev_critical_ind - first_critical_ind\n \n return res\n```\n``` C++ []\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n vector<int> res(2, -1);\n int prev_critical_ind = -1, first_critical_ind = -1;\n ListNode* prev = head;\n ListNode* cur = head->next;\n int cur_ind = 1;\n\n while (cur->next != nullptr) {\n if ((cur->val > prev->val && cur->val > cur->next->val) ||\n (cur->val < prev->val && cur->val < cur->next->val)) {\n if (prev_critical_ind != -1) {\n res[0] = (res[0] == -1) ? cur_ind - prev_critical_ind : min(res[0], cur_ind - prev_critical_ind);\n } else {\n first_critical_ind = cur_ind;\n }\n prev_critical_ind = cur_ind;\n }\n prev = cur;\n cur = cur->next;\n cur_ind++;\n }\n\n if (prev_critical_ind != -1 && prev_critical_ind != first_critical_ind) {\n res[1] = prev_critical_ind - first_critical_ind;\n }\n\n return res;\n }\n};\n```\n``` JavaScript []\nvar nodesBetweenCriticalPoints = function(head) {\n let res = [-1, -1];\n let prev_critical_ind = null, first_critical_ind = null;\n let prev = head;\n let cur = head.next;\n let cur_ind = 1;\n\n while (cur.next !== null) {\n if ((cur.val > prev.val && cur.val > cur.next.val) || \n (cur.val < prev.val && cur.val < cur.next.val)) {\n if (prev_critical_ind !== null) {\n res[0] = (res[0] === -1) ? cur_ind - prev_critical_ind : Math.min(res[0], cur_ind - prev_critical_ind);\n } else {\n first_critical_ind = cur_ind;\n }\n prev_critical_ind = cur_ind;\n }\n prev = cur;\n cur = cur.next;\n cur_ind++;\n }\n\n if (prev_critical_ind !== null && prev_critical_ind !== first_critical_ind) {\n res[1] = prev_critical_ind - first_critical_ind;\n }\n\n return res;\n};\n```\n``` Java []\nclass Solution {\n public int[] nodesBetweenCriticalPoints(ListNode head) {\n int[] res = new int[]{-1, -1};\n Integer prev_critical_ind = null, first_critical_ind = null;\n ListNode prev = head;\n ListNode cur = head.next;\n int cur_ind = 1;\n\n while (cur.next != null) {\n if ((cur.val > prev.val && cur.val > cur.next.val) ||\n (cur.val < prev.val && cur.val < cur.next.val)) {\n if (prev_critical_ind != null) {\n res[0] = (res[0] == -1) ? cur_ind - prev_critical_ind : Math.min(res[0], cur_ind - prev_critical_ind);\n } else {\n first_critical_ind = cur_ind;\n }\n prev_critical_ind = cur_ind;\n }\n prev = cur;\n cur = cur.next;\n cur_ind++;\n }\n\n if (prev_critical_ind != null && !prev_critical_ind.equals(first_critical_ind)) {\n res[1] = prev_critical_ind - first_critical_ind;\n }\n\n return res;\n }\n}\n```\n``` C []\nint* nodesBetweenCriticalPoints(struct ListNode* head, int* returnSize) {\n int* res = (int*)malloc(2 * sizeof(int));\n res[0] = -1;\n res[1] = -1;\n int prev_critical_ind = -1, first_critical_ind = -1;\n struct ListNode* prev = head;\n struct ListNode* cur = head->next;\n int cur_ind = 1;\n\n while (cur->next != NULL) {\n if ((cur->val > prev->val && cur->val > cur->next->val) ||\n (cur->val < prev->val && cur->val < cur->next->val)) {\n if (prev_critical_ind != -1) {\n res[0] = (res[0] == -1) ? cur_ind - prev_critical_ind : (cur_ind - prev_critical_ind < res[0] ? cur_ind - prev_critical_ind : res[0]);\n } else {\n first_critical_ind = cur_ind;\n }\n prev_critical_ind = cur_ind;\n }\n prev = cur;\n cur = cur->next;\n cur_ind++;\n }\n\n if (prev_critical_ind != -1 && prev_critical_ind != first_critical_ind) {\n res[1] = prev_critical_ind - first_critical_ind;\n }\n\n *returnSize = 2;\n return res;\n}\n```\n\n\n## \uD83D\uDCA1\uD83D\uDCA1\uD83D\uDCA1I encourage you to check out [my profile](https://leetcode.com/heir-of-god/) and [Project-S](https://github.com/Heir-of-God/Project-S) project for detailed explanations and code for different problems (not only Leetcode). Happy coding and learning!\uD83D\uDCDA\n\n### Please consider *upvote*\u2B06\uFE0F\u2B06\uFE0F\u2B06\uFE0F because I try really hard not just to put here my code and rewrite testcase to show that it works but explain you WHY it works and HOW. Thank you\u2764\uFE0F\n\n## If you have any doubts or questions feel free to ask them in comments. I will be glad to help you with understanding\u2764\uFE0F\u2764\uFE0F\u2764\uFE0F\n\n![There is image for upvote](https://assets.leetcode.com/users/images/fde74702-a4f6-4b9f-95f2-65fa9aa79c48_1716995431.3239644.png)\n
46
38
['Array', 'Linked List', 'Two Pointers', 'C', 'Python', 'C++', 'Java', 'Python3', 'JavaScript']
11
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
🔥🔥Beats 100% | Easy Solution with explanation in java,c++
beats-100-easy-solution-with-explanation-v0ep
\n\n# Code\njava []\nclass Solution {\n public int[] nodesBetweenCriticalPoints(ListNode head) {\n ListNode prev = head;\n head = head.next;\n
santhosh_kumar_13
NORMAL
2024-07-05T03:33:53.037831+00:00
2024-07-11T02:01:27.642685+00:00
3,282
false
\n\n# Code\n```java []\nclass Solution {\n public int[] nodesBetweenCriticalPoints(ListNode head) {\n ListNode prev = head;\n head = head.next;\n int i = 1, mindist = Integer.MAX_VALUE, prev_i = Integer.MIN_VALUE, first_i = -1;\n while (head.next != null) {\n if ((prev.val < head.val && head.val > head.next.val) || (prev.val > head.val && head.val < head.next.val)) {\n if (prev_i != Integer.MIN_VALUE) {\n mindist = Math.min(mindist, i - prev_i);\n }\n if (first_i == -1) {\n first_i = i;\n }\n prev_i = i;\n }\n prev = head;\n head = head.next;\n i++;\n }\n if (mindist == Integer.MAX_VALUE) {\n return new int[] {-1, -1};\n }\n return new int[] {mindist, prev_i - first_i};\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n ListNode* prev = head;\n head = head->next;\n int i = 1, mindist = INT_MAX, prev_i = INT_MIN, first_i = -1;\n\n while (head->next != nullptr) {\n if ((prev->val < head->val && head->val > head->next->val) || \n (prev->val > head->val && head->val < head->next->val)) {\n if (prev_i != INT_MIN) {\n mindist = min(mindist, i - prev_i);\n }\n if (first_i == -1) {\n first_i = i;\n }\n prev_i = i;\n }\n prev = head;\n head \n if (mindist == INT_MAX) {\n return {-1, -1};\n }\n\n return {mindist, prev_i - first_i};\n }\n};\n```\n\n---\n![image.png](https://assets.leetcode.com/users/images/6e533dc2-b703-4d0c-802c-e7fe805e70bb_1720150349.002366.png)\n\n
39
2
['C++', 'Java']
5
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Java Solution, Beats 100.00%
java-solution-beats-10000-by-mohit-005-fu1p
Intuition\n\nThe problem requires finding critical points in a linked list and then determining the minimum and maximum distances between these critical points.
Mohit-005
NORMAL
2024-07-05T02:16:20.129516+00:00
2024-07-05T02:16:20.129544+00:00
2,174
false
# Intuition\n\nThe problem requires finding critical points in a linked list and then determining the minimum and maximum distances between these critical points. A critical point in a linked list is defined as a node that is either a local maximum or a local minimum. The key challenge is to efficiently identify these critical points and compute the required distances.\n\n# Approach\n\n1. **Initialization**: \n - Initialize variables to track the indices of the first and last critical points.\n - Use a variable to store the smallest distance found between any two critical points.\n - Keep track of the value of the previous node to compare it with the current node and the next node.\n\n2. **Traversal**:\n - Traverse the linked list starting from the second node.\n - For each node, check if it is a critical point by comparing it with its previous and next nodes.\n - If a node is a critical point:\n - Update the first critical point index if it is the first critical point found.\n - Calculate the distance from the last critical point and update the smallest distance if necessary.\n - Update the last critical point index.\n - Move to the next node and update the previous node\'s value.\n\n3. **Result Calculation**:\n - If no critical points or only one critical point is found, return `[-1, -1]`.\n - Otherwise, return an array with the smallest distance and the distance between the first and last critical points.\n\n# Complexity\n\n## Time Complexity\n- The solution involves a single pass through the linked list, making the time complexity **O(n)**, where **n** is the number of nodes in the linked list. Each node is processed once to determine if it is a critical point and to update the distances.\n\n## Space Complexity\n- The space complexity is **O(1)** because the solution uses a fixed amount of extra space regardless of the size of the input linked list. The only extra space used is for a few integer variables to store indices and distances.\n\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public int[] nodesBetweenCriticalPoints(ListNode head) {\n // Initialize necessary variables\n int firstCriticalIndex = -1;\n int lastCriticalIndex = -1;\n int smallestDistance = Integer.MAX_VALUE;\n int prevValue = head.val;\n \n ListNode currentNode = head.next;\n int currentIndex = 1;\n \n // Traverse the list\n while (currentNode != null && currentNode.next != null) {\n // Check if the current node is a critical point\n if ((prevValue < currentNode.val && currentNode.val > currentNode.next.val) || \n (prevValue > currentNode.val && currentNode.val < currentNode.next.val)) {\n \n // If it\'s the first critical point found, set firstCriticalIndex\n if (firstCriticalIndex == -1) {\n firstCriticalIndex = currentIndex;\n } else {\n // Update the smallest distance if not the first critical point\n smallestDistance = Math.min(smallestDistance, currentIndex - lastCriticalIndex);\n }\n \n // Update the last critical point index\n lastCriticalIndex = currentIndex;\n }\n \n // Move to the next node\n prevValue = currentNode.val;\n currentNode = currentNode.next;\n currentIndex++;\n }\n \n // If no or only one critical point is found\n if (firstCriticalIndex == -1 || lastCriticalIndex == firstCriticalIndex) {\n return new int[] {-1, -1};\n }\n \n // Return the minimum and maximum distances between critical points\n return new int[] {smallestDistance, lastCriticalIndex - firstCriticalIndex};\n }\n}\n\n```\n\n# Summary\n- **Intuition**: Identify critical points in the list and compute distances between them.\n- **Approach**: Traverse the list, identify critical points, and update distances.\n- **Time Complexity**: **O(n)** due to single traversal of the list.\n- **Space Complexity**: **O(1)** due to constant extra space usage.
39
1
['Java']
3
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
2058. Find the Minimum and Maximum Number of Nodes Between Critical Points
2058-find-the-minimum-and-maximum-number-rg8c
Code\n\nclass Solution {\n public int[] nodesBetweenCriticalPoints(ListNode head) {\n int[] ans = {-1, -1};\n if (head == null || head.next ==
DoaaOsamaK
NORMAL
2024-07-05T03:12:53.973157+00:00
2024-07-05T03:12:53.973180+00:00
658
false
# Code\n```\nclass Solution {\n public int[] nodesBetweenCriticalPoints(ListNode head) {\n int[] ans = {-1, -1};\n if (head == null || head.next == null || head.next.next == null) return ans;\n\n ListNode pre = head;\n ListNode cur = head.next;\n int prePosition = -1, curPosition = -1, firstPosition = -1, position = 1;\n\n while (cur.next != null) {\n ListNode next = cur.next;\n if ((cur.val < pre.val && cur.val < next.val) || (cur.val > pre.val && cur.val > next.val)) {\n prePosition = curPosition;\n curPosition = position;\n if (firstPosition == -1) {\n firstPosition = position;\n }\n if (prePosition != -1) {\n if (ans[0] == -1) {\n ans[0] = curPosition - prePosition;\n } else {\n ans[0] = Math.min(ans[0], curPosition - prePosition);\n }\n ans[1] = position - firstPosition;\n }\n }\n pre = cur;\n cur = next;\n position++;\n }\n return ans;\n }\n}\n\n```
36
0
['Java']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
✅ Short & Easy | c++
short-easy-c-by-rajat_gupta-7jor
TC : O(n)\nSC : O(n)\n\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n ListNode *prev=head;\n head=head
rajat_gupta_
NORMAL
2021-10-31T04:01:42.554940+00:00
2021-10-31T04:16:12.224441+00:00
3,782
false
**TC : O(n)\nSC : O(n)**\n```\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n ListNode *prev=head;\n head=head->next;\n int i=1;\n vector<int> index;\n while(head->next){\n if((prev->val < head->val and head->val > head->next->val) ||( prev->val > head->val and head->val < head->next->val)){\n index.push_back(i);\n }\n prev=head;\n head=head->next;\n i++;\n }\n if(index.size() < 2) return {-1,-1};\n \n int mindist=INT_MAX;\n for(int i=0;i<index.size()-1;i++){\n mindist=min(index[i+1]-index[i],mindist);\n }\n return {mindist,index.back()-index[0]};\n }\n};\n```\n**TC : O(n)\nSC : O(1)**\n```\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n ListNode *prev=head;\n head=head->next;\n int i=1,mindist=INT_MAX,prev_i=INT_MIN,first_i=-1;\n while(head->next){\n if((prev->val < head->val and head->val > head->next->val) ||( prev->val > head->val and head->val < head->next->val)){\n if(prev_i!=INT_MIN) mindist=min(mindist,i-prev_i);\n if(first_i==-1) first_i=i;\n prev_i=i;\n }\n prev=head;\n head=head->next;\n i++;\n }\n if(mindist==INT_MAX) return {-1,-1};\n return {mindist,prev_i-first_i};\n }\n};\n```\n**Feel free to ask any question in the comment section.**\nI hope that you\'ve found the solution useful.\nIn that case, **please do upvote and encourage me** to on my quest to document all leetcode problems\uD83D\uDE03\nHappy Coding :)\n
36
6
['C', 'C++']
4
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Python 3 || 11 lines, w/ explanation || T/S: 82% / 88%
python-3-11-lines-w-explanation-ts-82-88-dh7a
\nclass Solution:\n def nodesBetweenCriticalPoints(self, head: ListNode) -> List[int]:\n\n ct, critPts, prev = 0, [], head.val
Spaulding_
NORMAL
2022-10-18T21:56:45.564852+00:00
2024-07-05T03:37:15.774574+00:00
796
false
```\nclass Solution:\n def nodesBetweenCriticalPoints(self, head: ListNode) -> List[int]:\n\n ct, critPts, prev = 0, [], head.val # keep track of node-count, critical points\n # encountered, and previous node value\n while head.next:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Tests for critical points: product < 0 if and only if\n if (prev-head.val)*(head.val-head.next.val) < 0: # prev < head.val > head.next.val, or \n critPts.append(ct) # prev > head.val < head.next.val\n \n prev, head = head.val, head.next # iterates to next node and increments node-count\n ct+= 1\n\n n = len(critPts) # fewer than 2 nodes\n if n < 2: return [-1,-1]\n\n mn = min((critPts[i]-critPts[i-1] for i in range(1, n))) # list already sorted, so min is least dist between \n mx = critPts[-1] - critPts[0] # consecutive elements; max is last element - 1st element\n\n return [mn, mx]\n```\n\n[https://leetcode.com/problems/find-the-minimum-and-maximum-number-of-nodes-between-critical-points/submissions/1285359650/](https://leetcode.com/problems/find-the-minimum-and-maximum-number-of-nodes-between-critical-points/submissions/1285359650/)\n\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(*N*), in which *N* ~ the number nodes in the list.
14
0
['Python', 'Python3']
1
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
😍 BEGINNERS FRIENDLY ||✅ 💯% ON RUNTIME ||✌️ EASY || O(n) 🏃‍♂️ AND O(1) 🚀
beginners-friendly-on-runtime-easy-on-an-e8vg
Intuition \uD83D\uDCA1\n Describe your first thoughts on how to solve this problem. \n\nThe problem seems to involve identifying critical points in a singly-lin
IamHazra
NORMAL
2024-03-25T19:56:20.636556+00:00
2024-03-25T19:59:10.835990+00:00
507
false
# Intuition \uD83D\uDCA1\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nThe problem seems to involve identifying critical points in a singly-linked list and calculating the distances between them. One potential approach could be to iterate through the list while keeping track of critical points where the value is either higher or lower than its adjacent nodes. By maintaining indices of these critical points and calculating distances between them, we can determine the required output.\n\n# Approach \uD83D\uDEE0\uFE0F\n<!-- Describe your approach to solving the problem. -->\n\n1. **Initialize Variables:** Start by initializing variables and an array to store the results.\n2. **Iterate Through the List:** Traverse the linked list, examining each triplet of nodes.\n3. **Identify Critical Points:** Determine critical points where the middle node has a value higher or lower than its adjacent nodes.\n4. **Calculate Distances:** Compute distances between critical points and update the minimum distance found so far.\n5. **Return Results:** Return the calculated distances.\n\n# Complexity \uD83D\uDCCA\n- **Time Complexity:** The time complexity of this solution is O(n), where n is the number of nodes in the linked list. We iterate through the list once to identify critical points and calculate distances.\n- **Space Complexity:** The space complexity is O(1). We are using a constant amount of extra space for variables regardless of the size of the input linked list.\n\n# Code \uD83D\uDCBB\n```java []\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public int[] nodesBetweenCriticalPoints(ListNode head) {\n int[] array = new int[2];\n if (head == null || head.next == null || head.next.next == null) {\n return new int[] {-1, -1};\n }\n ListNode first = head;\n ListNode second = head.next;\n ListNode third = head.next.next;\n int index = 2, greater = -1, min = Integer.MAX_VALUE, minDistance = Integer.MAX_VALUE;\n while (third != null) {\n if ((second.val > first.val && second.val > third.val) || (second.val < first.val && second.val < third.val)) {\n if (greater != -1) {\n int diff = index - greater;\n if (minDistance > diff) {\n minDistance = diff;\n }\n }\n greater = index;\n if (min > greater) {\n min = greater;\n }\n }\n index++;\n first = first.next;\n second = second.next;\n third = third.next;\n }\n array[0] = minDistance == Integer.MAX_VALUE ? -1 : minDistance;\n array[1] = (min == Integer.MAX_VALUE || min == greater) ? array[0] : greater - min;\n return array;\n }\n}\n```\n```C++ []\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n vector<int> array(2, 0);\n if (!head || !head->next || !head->next->next) {\n return {-1, -1};\n }\n ListNode* first = head;\n ListNode* second = head->next;\n ListNode* third = head->next->next;\n int index = 2, greater = -1, min = INT_MAX, minDistance = INT_MAX;\n while (third) {\n if ((second->val > first->val && second->val > third->val) || (second->val < first->val && second->val < third->val)) {\n if (greater != -1) {\n int diff = index - greater;\n if (minDistance > diff) {\n minDistance = diff;\n }\n }\n greater = index;\n if (min > greater) {\n min = greater;\n }\n }\n index++;\n first = first->next;\n second = second->next;\n third = third->next;\n }\n array[0] = minDistance == INT_MAX ? -1 : minDistance;\n array[1] = (min == INT_MAX || min == greater) ? array[0] : greater - min;\n return array;\n }\n};\n```\n```javascript []\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @return {number[]}\n */\nvar nodesBetweenCriticalPoints = function(head) {\n const array = [0, 0];\n if (!head || !head.next || !head.next.next) {\n return [-1, -1];\n }\n let first = head;\n let second = head.next;\n let third = head.next.next;\n let index = 2, greater = -1, min = Number.MAX_SAFE_INTEGER, minDistance = Number.MAX_SAFE_INTEGER;\n while (third) {\n if ((second.val > first.val && second.val > third.val) || (second.val < first.val && second.val < third.val)) {\n if (greater !== -1) {\n const diff = index - greater;\n if (minDistance > diff) {\n minDistance = diff;\n }\n }\n greater = index;\n if (min > greater) {\n min = greater;\n }\n }\n index++;\n first = first.next;\n second = second.next;\n third = third.next;\n }\n array[0] = minDistance === Number.MAX_SAFE_INTEGER ? -1 : minDistance;\n array[1] = (min === Number.MAX_SAFE_INTEGER || min === greater) ? array[0] : greater - min;\n return array;\n};\n```\n\n```\n\n IF MY CODE IS HELPFUL THEN UPVOTE \uD83D\uDC4D\n```\n
12
0
['Linked List', 'Math', 'Two Pointers', 'C++', 'Java', 'JavaScript']
1
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
One Pass Explained | Time O(N) | Space O(1)
one-pass-explained-time-on-space-o1-by-n-r7qy
Keep Two Pointers - One for traversing "curr" in my solution and "prev" to track last node\n To make solution simple declare variables for minDistance with larg
nikhilnagrale2
NORMAL
2021-11-02T22:47:01.571996+00:00
2021-11-20T15:46:11.798041+00:00
1,199
false
* Keep Two Pointers - One for traversing "curr" in my solution and "prev" to track last node\n* To make solution simple declare variables for minDistance with large value, maxDistance as smallest value, length (size), First Critical Point ( first ) and Previous Critical Point ( preCP ).\n* While traversing a linkedList check if it is Local Maxima or Local Minima\n* For the first Local Maxima/Minima we will only update firstCP variable as having lesser than two CP we can\'t find distance hence ```return {-1,-1};```\n* For all next LocalMinima Or Maxima we will update as follows \n```\nminDistance = min(minDistance, size - preCP); // difference of just prev and curr CP\nmaxDistance = max(maxDistance, size - first); // difference of first and curr CP\n```\nLastly \n```\nreturn {minDistance == INT_MAX ? -1 : minDistance, maxDistance};\n```\n\nCode\n\n```\nclass Solution {\n public:\n vector<int> nodesBetweenCriticalPoints(ListNode *head) {\n ListNode *curr = head, *prev = NULL;\n int minDistance = INT_MAX, maxDistance = -1, size = 0, preCP = 0,\n first = 0;\n while (curr) {\n if (curr->next && prev) {\n if ((curr->val < prev->val && curr->val < curr->next->val) ||\n (curr->val > prev->val && curr->val > curr->next->val)) {\n if (first == 0) {\n first = size;\n } else {\n minDistance = min(minDistance, size - preCP);\n maxDistance = max(maxDistance, size - first);\n }\n preCP = size;\n }\n }\n size++;\n prev = curr;\n curr = curr->next;\n }\n return {minDistance == INT_MAX ? -1 : minDistance, maxDistance};\n }\n};\n```\n\n```\nTime Complexity - O(N)\nSpace Complexity - O(1)\n```\n**Feel free to ask any question in the comment section.**
12
1
['Linked List', 'C']
1
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Best solution which is no less than EDITORIAL.. beats 98.6% users..
best-solution-which-is-no-less-than-edit-ofgu
\n\n# Code\n\nclass Solution:\n def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:\n result = [-1, -1]\n\n # Initiali
Aim_High_212
NORMAL
2024-07-05T01:43:17.806051+00:00
2024-07-05T01:43:17.806072+00:00
40
false
\n\n# Code\n```\nclass Solution:\n def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:\n result = [-1, -1]\n\n # Initialize minimum distance to the maximum possible value\n min_distance = float("inf")\n\n # Pointers to track the previous node, current node, and indices\n previous_node = head\n current_node = head.next\n current_index = 1\n previous_critical_index = 0\n first_critical_index = 0\n\n while current_node.next is not None:\n # Check if the current node is a local maxima or minima\n if (\n current_node.val < previous_node.val\n and current_node.val < current_node.next.val\n ) or (\n current_node.val > previous_node.val\n and current_node.val > current_node.next.val\n ):\n\n # If this is the first critical point found\n if previous_critical_index == 0:\n previous_critical_index = current_index\n first_critical_index = current_index\n else:\n # Calculate the minimum distance between critical points\n min_distance = min(\n min_distance, current_index - previous_critical_index\n )\n previous_critical_index = current_index\n\n # Move to the next node and update indices\n current_index += 1\n previous_node = current_node\n current_node = current_node.next\n\n # If at least two critical points were found\n if min_distance != float("inf"):\n max_distance = previous_critical_index - first_critical_index\n result = [min_distance, max_distance]\n\n return result\n \n```
9
0
['Linked List', 'C', 'Python', 'C++', 'Java', 'Python3']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Easy solution (imo). TC - O(n), SC - O(n)
easy-solution-imo-tc-on-sc-on-by-movsar-1e1m
python\nclass Solution:\n def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:\n # Initialize pointers for traversing the list
movsar
NORMAL
2024-07-05T00:59:49.716404+00:00
2024-07-05T07:11:16.240073+00:00
873
false
```python\nclass Solution:\n def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:\n # Initialize pointers for traversing the list\n left = head\n mid = head.next\n\n # Check if the list has at least three nodes\n if not mid.next:\n return [-1, -1]\n\n right = mid.next\n\n idx = 2 # Index of the current middle node\n idxs = [] # List to store indices of critical points\n\n # Traverse the list\n while right:\n # Check for local maxima or minima\n if (mid.val > left.val and mid.val > right.val) or (mid.val < left.val and mid.val < right.val):\n idxs.append(idx)\n\n # Move to the next set of nodes\n left = mid\n mid = right\n right = right.next\n idx += 1\n\n # If there are fewer than two critical points, return [-1, -1]\n if len(idxs) < 2:\n return [-1, -1]\n\n # Find the minimum and maximum distances between critical points\n min_distance = float(\'inf\')\n max_distance = idxs[-1] - idxs[0]\n\n for i in range(1, len(idxs)):\n min_distance = min(min_distance, idxs[i] - idxs[i - 1])\n\n return [min_distance, max_distance]\n\n```
9
1
['Python3']
4
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Short and Easy c++ , Beginner Friendly.
short-and-easy-c-beginner-friendly-by-rn-n5b1
This is a very simple approach and easy to understand for beginners \nFor sake of understanding \nlets consider a example :\n Input: head = [5,3,1,2,5,1,2]\n s
rnurchal
NORMAL
2021-10-31T04:45:39.852350+00:00
2021-10-31T04:45:39.852378+00:00
705
false
This is a very simple approach and easy to understand for beginners \nFor sake of understanding \nlets consider a example :\n Input: head = [5,3,1,2,5,1,2]\n so here what will be the next step;\n lets take a empty vector of int;\n i have attached a image check it out.\n 1. it will [![image](https://assets.leetcode.com/users/images/840afcfb-b46e-44fd-acf7-4dbef33ae504_1635655499.54518.jpeg)\n]\n\'\'\'\n**class Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n if(!head || !head->next || !head->next->next) return {-1,-1};\n ListNode *prev=head;\n head=head->next;\n \n \n \n vector<int> index;\n int i = 1;\n while(head->next){\n if((prev->val < head->val && head->val > head->next->val) ||( prev->val > head->val && head->val < head->next->val)){\n index.push_back(i);\n }\n prev=head;\n head=head->next;\n i++;\n }\n \n if(index.size() < 2)\n return {-1,-1};\n int localminima = INT_MAX;\n for(int l = 0 ; l < index.size()-1;l++)\n {\n localminima = min(index[l+1] - index[l],localminima);\n }\n \n return {localminima , index.back()-index[0]};\n }**\n};\n\'\'\'\nTC - 0(N)\nSC - 0(N);
8
0
[]
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Finding Distances Between Critical Points in a Linked List
finding-distances-between-critical-point-r2q0
Intuition\n Describe your first thoughts on how to solve this problem. \nTo determine the minimum and maximum distances between critical points in a linked list
iamanrajput
NORMAL
2024-07-05T10:24:30.819540+00:00
2024-07-05T10:24:30.819564+00:00
235
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo determine the minimum and maximum distances between critical points in a linked list, we need to identify nodes that are either local maxima or minima. These nodes are surrounded by nodes with smaller or larger values, respectively. By iterating through the linked list, we can track the positions of these critical points and compute the required distances.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nInitialization:\n\n-Use three pointers: prev to point to the previous node, curr to point to the current node, and next to point to the next node.\n\n-Use variables first and last to store the positions of the first and the last critical points.\n\n-Use an index i to keep track of the current position in the linked list.\n\n-Initialize an array ans with two elements: the first element set to a large value (Integer.MAX_VALUE) to keep track of the minimum distance, and the second element set to a small value (Integer.MIN_VALUE) to keep track of the maximum distance.\n\nIterate through the list:\n\n-Traverse the linked list starting from the second node to the second-to-last node.\n\n-Check if the current node is a local maxima or minima by comparing its value with the values of the previous and next nodes.\n\nIf a critical point is found:\n\n-If it\'s the first critical point, update both first and last with the current position.\n\n-For subsequent critical points, update the minimum distance in ans[0] and the maximum distance in ans[1], and update last to the current position.\n\nResult:\n\n-If no critical points or only one critical point is found, return [-1, -1].\n\n-Otherwise, return the computed minimum and maximum distances.\n# Complexity\n- Time complexity: O(n), where n is the number of nodes in the linked list. We only need a single pass through the list to identify critical points and compute distances.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1), as we use a constant amount of extra space for variables and the result array.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n\n public int[] nodesBetweenCriticalPoints(ListNode head) {\n ListNode prev = head;\n ListNode curr = head.next;\n int first = 0, last = 0;\n int i = 1;\n int[] ans = new int[] {Integer.MAX_VALUE, Integer.MIN_VALUE};\n while (curr.next != null) {\n if (curr.val < Math.min(prev.val, curr.next.val)\n || curr.val > Math.max(prev.val, curr.next.val)) {\n if (last == 0) {\n first = i;\n last = i;\n } else {\n ans[0] = Math.min(ans[0], i - last);\n ans[1] = i - first;\n last = i;\n }\n }\n i++;\n prev = curr;\n curr = curr.next;\n }\n return first == last ? new int[] {-1, -1} : ans;\n }\n}\n```
7
0
['Linked List', 'C++', 'Java']
1
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
simple and easy C++ solution 😍❤️‍🔥
simple-and-easy-c-solution-by-shishirrsi-azpl
if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n\n# Code\n\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) \n {\
shishirRsiam
NORMAL
2024-07-05T03:42:01.798195+00:00
2024-07-05T03:42:01.798227+00:00
1,676
false
# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) \n {\n vector<int>store;\n\n int ans1 = INT_MAX, cur, next, n;\n int last = head->val, position = 2;\n\n while(head->next)\n {\n cur = head->val, next = head->next->val;\n\n if((last > cur and cur < next) or (last < cur and cur > next)) \n store.push_back(position);\n position++;\n last = cur, head = head->next;\n\n n = store.size();\n if(n > 1) ans1 = min(ans1, store[n-1] - store[n-2]);\n }\n \n if(ans1 == INT_MAX) return {-1, -1};\n \n return {ans1, store.back() - store[0]};\n }\n};\n```
7
0
['Linked List', 'C++']
3
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Python || Easy Solution
python-easy-solution-by-naveenrathore-x3se
class Solution:\n\t\n\tdef nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:\n \n prev = None\n temp = head\n
naveenrathore
NORMAL
2021-11-04T09:08:46.679231+00:00
2021-11-04T09:08:46.679259+00:00
1,145
false
class Solution:\n\t\n\tdef nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:\n \n prev = None\n temp = head\n \n mini, maxi = 10 ** 5, 0\n count = 1\n \n diff = 10 ** 5\n while temp.next.next != None:\n prev = temp\n temp = temp.next\n count += 1\n \n if prev.val > temp.val < temp.next.val or prev.val < temp.val > temp.next.val:\n \n if maxi != 0:\n mini = min(mini, count - maxi)\n diff = min(diff, count)\n maxi = count\n \n if diff == 10 ** 5 or mini == 10 ** 5:\n return [-1, -1]\n return [mini, maxi - diff]\n\t\t\n# if you like the solution, Please upvote!!
7
2
['Linked List', 'Python', 'Python3']
1
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
BEET 100%
beet-100-by-ayu7054-jdpn
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
Ayu7054
NORMAL
2023-12-20T08:48:51.895259+00:00
2023-12-20T08:48:51.895283+00:00
139
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:\n temp,lst=head.next,[]\n prev=head\n i=1\n count=0\n while temp.next:\n if (prev.val<temp.val and temp.val>temp.next.val) or (prev.val>temp.val and temp.val<temp.next.val):\n lst.append(i)\n count+=1\n i+=1\n temp=temp.next\n prev=prev.next\n if count<2:\n return [-1,-1]\n else:\n res=[]\n min1=lst[-1]\n for i in range(len(lst)-1):\n min1=min(min1,(lst[i+1]-lst[i]))\n res.append(min1) \n res.append(lst[-1]-lst[0])\n return res \n \n```
6
0
['Python3']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Easy JAVA soln, beats 100%, without using array/arraylist
easy-java-soln-beats-100-without-using-a-5ua3
Traversing the Linked-List to check for the critical points and maintaining theminimum_index , last_index and current_index\nAlso checking for the minimum dista
waynebruce1704
NORMAL
2021-10-31T10:06:56.611069+00:00
2021-10-31T10:06:56.611110+00:00
1,131
false
Traversing the Linked-List to check for the critical points and maintaining the` minimum_index , last_index and current_index`\nAlso checking for the minimum distance between the critical point index at each traversal.\nThe maximum distance at end of traversal will be `current_index - minimum_index`\n\n```\nclass Solution {\n public int[] nodesBetweenCriticalPoints(ListNode head) {\n int res[]=new int[]{-1,-1};\n if(head==null||head.next==null||head.next.next==null) return res;\n int minidx=Integer.MAX_VALUE,curridx=-1,lastidx=-1;\n ListNode prev=head,ptr=head.next;\n int idx=1,minD=Integer.MAX_VALUE;\n while(ptr!=null&&ptr.next!=null){\n if((ptr.val>prev.val&&ptr.val>ptr.next.val)||(ptr.val<prev.val&&ptr.val<ptr.next.val)){\n if(idx<minidx) minidx=idx;\n lastidx=curridx;\n curridx=idx;\n if(lastidx!=-1&&curridx-lastidx<minD) minD=curridx-lastidx;\n }\n prev=ptr;\n ptr=ptr.next;\n idx++;\n }\n if(lastidx==-1) return res;\n else{\n res[0]=minD;\n res[1]=curridx-minidx;\n }\n return res;\n }\n}\n```
6
1
['Linked List', 'Java']
1
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
simple and easy Python solution 😍❤️‍🔥
simple-and-easy-python-solution-by-shish-skj3
if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n\n# Code\n\nclass Solution(object):\n def nodesBetweenCriticalPoints(self, head):\n store = []\n
shishirRsiam
NORMAL
2024-07-05T03:51:32.398735+00:00
2024-07-05T03:51:32.398765+00:00
575
false
# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n\n# Code\n```\nclass Solution(object):\n def nodesBetweenCriticalPoints(self, head):\n store = []\n ans1 = float(\'inf\')\n last, position = head.val, 2\n head = head.next\n \n while head and head.next:\n cur, next_val = head.val, head.next.val\n\n if (last > cur < next_val) or (last < cur > next_val):\n store.append(position)\n\n position += 1\n last = cur\n head = head.next\n\n n = len(store)\n if n > 1:\n ans1 = min(ans1, store[n-1] - store[n-2])\n \n if ans1 == float(\'inf\'):\n return [-1, -1]\n \n return [ans1, store[-1] - store[0]]\n```
5
0
['Linked List', 'Python', 'Python3']
5
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Solution for LeetCode#2058
solution-for-leetcode2058-by-samir023041-famq
\n\n# Intuition\n Describe your first thoughts on how to solve this problem. \nWe need to iterate through the linked list to identify the critical points. As we
samir023041
NORMAL
2024-07-05T02:52:04.213068+00:00
2024-07-05T02:52:04.213091+00:00
62
false
![image.png](https://assets.leetcode.com/users/images/7c57799c-af3b-40cb-b88e-6c845aae5163_1720147365.7816968.png)\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe need to iterate through the linked list to identify the critical points. As we find each critical point, we should keep track of their positions and update the minimum and maximum distances accordingly.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Traverse the linked list while keeping track of the current index.\n2. Identify critical points by checking if the current node is a local minimum or maximum.\n3. Maintain the position of the first critical point, the last critical point, and the previous critical point.\n4. Calculate the minimum distance between consecutive critical points and the maximum distance between the first and last critical points.\n5. Return the results accordingly.\n\n# Complexity\n- Time complexity: O(n), where \uD835\uDC5B is the number of nodes in the linked list. We traverse the list only once.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1), as we only use a fixed amount of extra space.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public int[] nodesBetweenCriticalPoints(ListNode head) {\n int[] result={-1,-1};\n \n int firstIdx=-1;\n int lastIdx=-1;\n \n int idx=1;\n int minDistance=Integer.MAX_VALUE;\n //ListNode curr=head;\n while(head.next.next!=null){\n idx++;\n //Critial Nodes for local Maxima/Minima\n if( (head.val<head.next.val && head.next.val>head.next.next.val) || (head.val>head.next.val && head.next.val<head.next.next.val) ){\n if(firstIdx==-1){\n firstIdx=idx;\n lastIdx=idx;\n }\n else{\n minDistance=Math.min(minDistance, (idx-lastIdx));\n lastIdx=idx;\n } \n } \n \n head=head.next; \n }\n \n if( minDistance!=Integer.MAX_VALUE){\n result[0]=minDistance;\n result[1]=lastIdx-firstIdx;\n }\n \n //System.out.println("minDistance="+minDistance);\n //System.out.println("map="+map.toString());\n \n return result;\n }\n}\n```\n\n\n\n# Another Code\n![image.png](https://assets.leetcode.com/users/images/47369c9c-f508-4ee4-ab90-8d05c8969645_1720147818.5774431.png)\n\n\n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public int[] nodesBetweenCriticalPoints(ListNode head) {\n int[] result=new int[2];\n Arrays.fill(result, -1);\n \n TreeMap<Integer, Integer> map=new TreeMap();\n int idx=1;\n int minDistance=Integer.MAX_VALUE;\n //ListNode curr=head;\n while(head.next.next!=null){\n idx++;\n //Critial Nodes for local Maxima\n if(head.val<head.next.val && head.next.val>head.next.next.val){\n if(!map.isEmpty()){\n minDistance=Math.min(minDistance, (idx-map.lastKey()));\n }\n map.put(idx, head.next.val);\n } \n //Critical Nodes for local Minima\n else if(head.val>head.next.val && head.next.val<head.next.next.val){\n if(!map.isEmpty()){\n minDistance=Math.min(minDistance, (idx-map.lastKey()));\n }\n map.put(idx, head.next.val);\n }\n \n head=head.next; \n }\n \n if(!map.isEmpty() && minDistance!=Integer.MAX_VALUE){\n result[0]=minDistance;\n result[1]=map.lastKey()-map.firstKey();\n }\n \n //System.out.println("minDistance="+minDistance);\n //System.out.println("map="+map.toString());\n \n return result;\n }\n}\n```\n
5
0
['Java']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
C++ Simple and Clean Solution, Detailed Explanation, O(n) TC O(1) SC
c-simple-and-clean-solution-detailed-exp-m0px
Idea:\nWe loop through the list, and check each node if it\'s critical using helper function isCritical.\nIf it\'s critical, we save in mn the minimum distance
yehudisk
NORMAL
2021-10-31T10:37:39.488317+00:00
2021-10-31T10:37:39.488347+00:00
514
false
**Idea:**\nWe loop through the list, and check each node if it\'s critical using helper function `isCritical`.\nIf it\'s critical, we save in `mn` the minimum distance between two close critical points.\nWe also save in `first_crit` the index of the first critical point.\nLast, we update `prev_crit` to the current `idx`.\n\nOur result will be `{ mn, prev_crit - first_crit }`.\n\n**Time Complexity:** O(n)\n**Space Complexity:** O(1)\n```\nclass Solution {\npublic:\n int isCritical(ListNode* prev, ListNode* node) {\n if (prev->val < node->val && node->val > node->next->val) return true;\n if (prev->val > node->val && node->val < node->next->val) return true;\n return false;\n }\n \n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n int mn = INT_MAX, first_crit = -1, prev_crit = INT_MIN, idx = 1;\n ListNode* ptr = head->next, *prev = head;\n \n while (ptr->next) {\n \n if (isCritical(prev, ptr)) {\n if (prev_crit > INT_MIN) mn = min(mn, idx - prev_crit);\n if (first_crit == -1) first_crit = idx;\n prev_crit = idx;\n }\n \n idx++;\n prev = prev->next;\n ptr = ptr->next;\n }\n \n if (mn == INT_MAX) return {-1, -1};\n return {mn, prev_crit - first_crit};\n }\n};\n```\n**Like it? please upvote!**
5
1
['C']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Beats 95.89% Simple approach
beats-9589-simple-approach-by-prakhartya-0885
\n# Approach\nThe solution iterates through the linked list to identify critical points, storing their positions. It then calculates the minimum and maximum dis
prakhartyagi
NORMAL
2024-07-05T17:40:32.406170+00:00
2024-07-05T17:40:32.406189+00:00
5
false
\n# Approach\nThe solution iterates through the linked list to identify critical points, storing their positions. It then calculates the minimum and maximum distances between all pairs of these critical points. If fewer than two critical points are found, it returns {-1, -1}.\n\n# Complexity\n- Time complexity:\n O(N)\n\n- Space complexity:\n O(N)\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n vector<int> critical_points;\n if (!head || !head->next || !head->next->next) return {-1, -1};\n\n int mini = INT_MAX, maxi = INT_MIN;\n ListNode* tmp = head;\n int node_num = 1;\n\n while (tmp->next && tmp->next->next) {\n node_num++;\n if ((tmp->next->val > tmp->val && tmp->next->val > tmp->next->next->val) ||\n (tmp->next->val < tmp->val && tmp->next->val < tmp->next->next->val)) {\n critical_points.push_back(node_num);\n }\n tmp = tmp->next;\n }\n\n if (critical_points.size() < 2) return {-1, -1};\n\n maxi=critical_points.back()-critical_points.front();\n for (size_t i = 1; i < critical_points.size(); i++) {\n int diff = critical_points[i] - critical_points[i - 1];\n mini = min(mini, diff);\n }\n return {mini, maxi};\n }\n};\n\n```
4
0
['C++']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Solution Solved using the help of ZOO (jurel)
solution-solved-using-the-help-of-zoo-ju-jhl7
Intuition\n Describe your first thoughts on how to solve this problem. \nCreate a vector to store positions of the critical points, and return min and maximum d
udhaykondeti004
NORMAL
2024-07-05T16:27:15.413928+00:00
2024-07-05T16:27:15.413959+00:00
49
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCreate a vector to store positions of the critical points, and return min and maximum distances\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Take a pointer temp to store previous node and ptr to store current pointer\n- take a vector named position, and check whether the previous nodes and next nodes are greater or lesser than current node, if yes push the position\n- the index need to be increased parallely you visit a node\n- move the current and previous pointer to next\n- maximum distance will be the difference in the positions of last critical node and first critical node\n- for minimum distance we need to measure distance between consecutive positions and update accordingly\n- return distances in form of array {min,max};\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n ListNode* temp = head;\n ListNode* ptr = head->next;\n vector<int> position ;\n int index = 0;\n while(ptr->next!= NULL){\n index++;\n if(ptr->val<temp->val && ptr->val < ptr->next->val){\n position.push_back(index);\n }\n\n if(ptr->val > temp->val && ptr->val > ptr->next->val){\n position.push_back(index);\n }\n\n ptr = ptr->next;\n temp = temp->next;\n \n }\n\n if(position.size()<2) return{-1,-1};\n int max_dist = position[position.size()-1]-position[0];\n int min_dist = INT_MAX;\n int diff = 0;\n for(int i =0;i<position.size()-1;i++){\n diff = position[i+1] - position[i];\n if(diff<min_dist) min_dist = diff;\n }\n return {min_dist,max_dist};\n \n }\n};\n```
4
0
['C++']
5
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
2058. Find the Minimum and Maximum Number of Nodes || INTUITIVE || EASY || BEATS 90.46%
2058-find-the-minimum-and-maximum-number-51i3
\n\n# Intuition\n Describe your first thoughts on how to solve this problem. \nTraverse the linked list , comparing it with previous ans next node to find criri
k-arsyn28
NORMAL
2024-07-05T10:04:53.862462+00:00
2024-07-05T10:04:53.862500+00:00
12
false
![image.png](https://assets.leetcode.com/users/images/e0050e3a-94af-4747-acb2-b776e372725e_1720173559.6260934.png)\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTraverse the linked list , comparing it with previous ans next node to find crirical point and , updating current-pointer(`cp`), current-node-count(`c`), previous-pointer(`pp`), first-pointer(`fp`).\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Initialization:**\n Initialize pointers p, t, and n to traverse the linked list. p points to the current node, t points to the next node, and n points to the node after t.\n Initialize variables mini and maxi to keep track of the minimum and maximum distances between critical points.\n Initialize counters c (current position), cp (current critical point position), fp (first critical point position), and pp (previous critical point position).\n\n2. **Traversal and Critical Point Identification:**\n Traverse through the linked list using p, t, and n.\n Identify critical points where the value of t is greater than or less than both p and n (indicating a local maximum or minimum).\n\n3. **Distance Calculation:**\n Once a critical point is identified:\n Update cp and pp.\n Calculate the distance cp - pp and update mini.\n Update maxi with cp - fp if fp is valid (indicating the distance from the first critical point).\n\n4. **Edge Cases:**\n If no critical points are found (mini remains INT_MAX), return {-1, -1}.\n Otherwise, return the calculated distances as {mini, maxi}.\n\n# Complexity\n- Time complexity : **O(n)**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity : **O(1)**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n if(head->next->next == nullptr)\n return {-1,-1};\n \n ListNode* t = head->next;\n ListNode* p = head;\n ListNode* n = t->next;\n int mini = INT_MAX;\n int maxi = INT_MIN;\n\n\n int c = 1;\n int cp = -1;\n int fp=-1;\n int pp = -1;\n \n while(n != nullptr)\n {\n if(p->val < t->val && t->val > n->val || p->val > t->val && t->val < n->val)\n {\n pp = cp;\n cp = c;\n\n if(fp == -1)\n fp = c; \n }\n if(pp>0)\n {\n mini = min(mini,cp-pp);\n maxi =cp - fp;\n }\n c+=1;\n p = t;\n t = n;\n n = n->next;\n \n }\n \n \n return (mini==INT_MAX) ? vector<int>{-1,-1} : vector<int>{mini , maxi};\n }\n};\n```
4
0
['Linked List', 'C++']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Simple Java || C++ Code ☠️
simple-java-c-code-by-abhinandannaik1717-9uem
java []\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(i
abhinandannaik1717
NORMAL
2024-07-05T03:49:53.317275+00:00
2024-07-05T03:49:53.317305+00:00
479
false
```java []\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public int[] nodesBetweenCriticalPoints(ListNode head) {\n ListNode slow = head;\n ListNode med = slow.next;\n ListNode fast = med.next;\n int[] arr = new int[2];\n arr[0]=-1;\n arr[1]=-1;\n int minc=0,maxc=0,min=Integer.MAX_VALUE,max=0;\n boolean a = false;\n while(fast!=null){\n if((med.val>slow.val && med.val>fast.val) || (med.val<slow.val && med.val<fast.val)){\n a=true;\n if(maxc>max){\n max=maxc;\n }\n if(minc!=0 && minc<min){\n min=minc;\n }\n minc=0;\n }\n if(a==true){\n maxc++;\n minc++;\n }\n slow=med;\n med = fast;\n fast = fast.next;\n }\n if(max==0){\n return arr;\n }\n arr[0]=min;\n arr[1]=max;\n return arr;\n }\n}\n```\n```C++ []\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n ListNode* slow = head;\n ListNode* med = slow->next;\n ListNode* fast = med->next;\n vector<int> arr(2);\n arr[0]=-1;\n arr[1]=-1;\n int minc=0,maxc=0,min=INT_MAX,max=0;\n bool a = false;\n while(fast!=nullptr){\n if((med->val>slow->val && med->val>fast->val) || (med->val<slow->val && med->val<fast->val)){\n a=true;\n if(maxc>max){\n max=maxc;\n }\n if(minc!=0 && minc<min){\n min=minc;\n }\n minc=0;\n }\n if(a==true){\n maxc++;\n minc++;\n }\n slow=med;\n med = fast;\n fast = fast->next;\n }\n if(max==0){\n return arr;\n }\n arr[0]=min;\n arr[1]=max;\n return arr;\n }\n};\n```\n\n\n\n### Problem Understanding\n\nWe need to find the minimum and maximum distances between critical points in a linked list. A critical point is a local maxima or minima, defined as:\n- Local maxima: A node whose value is greater than both its previous and next nodes.\n- Local minima: A node whose value is smaller than both its previous and next nodes.\n\nIf there are fewer than two critical points, the result should be `[-1, -1]`.\n\n### Code Breakdown\n\n#### Definition and Initialization\n\n```java\nclass Solution {\n public int[] nodesBetweenCriticalPoints(ListNode head) {\n ListNode slow = head;\n ListNode med = slow.next;\n ListNode fast = med.next;\n int[] arr = new int[2];\n arr[0] = -1;\n arr[1] = -1;\n int minc = 0, maxc = 0, min = Integer.MAX_VALUE, max = 0;\n boolean a = false;\n```\n\n- **Pointers Initialization:**\n - `slow` points to the first node (`head`).\n - `med` points to the second node (`head.next`).\n - `fast` points to the third node (`head.next.next`).\n\n- **Array Initialization:**\n - `arr` is initialized to `[-1, -1]`, which will store the result `[minDistance, maxDistance]`.\n\n- **Counters and Flags:**\n - `minc` and `maxc` are counters for distances between critical points.\n - `min` is initialized to `Integer.MAX_VALUE` to find the minimum distance.\n - `max` is initialized to `0` to find the maximum distance.\n - `a` is a flag to check if at least one critical point is found.\n\n#### Traversing the List and Identifying Critical Points\n\n```java\n while (fast != null) {\n if ((med.val > slow.val && med.val > fast.val) || (med.val < slow.val && med.val < fast.val)) {\n a = true;\n if (maxc > max) {\n max = maxc;\n }\n if (minc != 0 && minc < min) {\n min = minc;\n }\n minc = 0;\n }\n if (a == true) {\n maxc++;\n minc++;\n }\n slow = med;\n med = fast;\n fast = fast.next;\n }\n```\n\n- **Condition Check for Critical Points:**\n - `(med.val > slow.val && med.val > fast.val)` checks if `med` is a local maxima.\n - `(med.val < slow.val && med.val < fast.val)` checks if `med` is a local minima.\n\n- **Updating Distances:**\n - If a critical point is found (`a = true`):\n - Update `max` if `maxc` is greater than the current `max`.\n - Update `min` if `minc` is non-zero and less than the current `min`.\n - Reset `minc` to `0` after each critical point.\n\n- **Incrementing Counters:**\n - `maxc` and `minc` are incremented if `a` is true, indicating that we have encountered at least one critical point.\n\n- **Pointer Movement:**\n - Move `slow`, `med`, and `fast` pointers to the next nodes.\n\n#### Final Result Calculation\n\n```java\n if (max == 0) {\n return arr;\n }\n arr[0] = min;\n arr[1] = max;\n return arr;\n }\n}\n```\n\n- **Check for Critical Points:**\n - If no critical points were found (`max == 0`), return `[-1, -1]`.\n\n- **Setting Result:**\n - If critical points are found, set `arr[0]` to `min` and `arr[1]` to `max`.\n\n### Example Walkthrough\n\nLet\'s walk through an example linked list: `1 -> 3 -> 2 -> 5 -> 4 -> 6 -> 1`\n\n1. **Initial Setup:**\n - `slow = 1`, `med = 3`, `fast = 2`\n - `arr = [-1, -1]`\n - `minc = 0`, `maxc = 0`, `min = Integer.MAX_VALUE`, `max = 0`, `a = false`\n\n2. **First Iteration:**\n - Check if `med` (`3`) is a critical point:\n - `med` is a local maxima (`3 > 1` and `3 > 2`).\n - `a = true`\n - `maxc` is not greater than `max`, so `max` remains `0`.\n - `minc` is `0`, so `min` remains `Integer.MAX_VALUE`.\n - Reset `minc` to `0`.\n - Increment `maxc` and `minc` (`maxc = 1`, `minc = 1`).\n - Move pointers (`slow = 3`, `med = 2`, `fast = 5`).\n\n3. **Second Iteration:**\n - Check if `med` (`2`) is a critical point:\n - `med` is a local minima (`2 < 3` and `2 < 5`).\n - `maxc` is `1`, so `max` remains `0`.\n - `minc` is `1`, so update `min` to `1`.\n - Reset `minc` to `0`.\n - Increment `maxc` and `minc` (`maxc = 2`, `minc = 1`).\n - Move pointers (`slow = 2`, `med = 5`, `fast = 4`).\n\n4. **Third Iteration:**\n - Check if `med` (`5`) is a critical point:\n - `med` is a local maxima (`5 > 2` and `5 > 4`).\n - `maxc` is `2`, so update `max` to `2`.\n - `minc` is `1`, so `min` remains `1`.\n - Reset `minc` to `0`.\n - Increment `maxc` and `minc` (`maxc = 3`, `minc = 1`).\n - Move pointers (`slow = 5`, `med = 4`, `fast = 6`).\n\n5. **Fourth Iteration:**\n - Check if `med` (`4`) is a critical point:\n - `med` is a local minima (`4 < 5` and `4 < 6`).\n - `maxc` is `3`, so update `max` to `3`.\n - `minc` is `1`, so `min` remains `1`.\n - Reset `minc` to `0`.\n - Increment `maxc` and `minc` (`maxc = 4`, `minc = 1`).\n - Move pointers (`slow = 4`, `med = 6`, `fast = 1`).\n\n6. **Fifth Iteration:**\n - Check if `med` (`6`) is a critical point:\n - `med` is a local maxima (`6 > 4` and `6 > 1`).\n - `maxc` is `4`, so update `max` to `4`.\n - `minc` is `1`, so `min` remains `1`.\n - Reset `minc` to `0`.\n - Increment `maxc` and `minc` (`maxc = 5`, `minc = 1`).\n - Move pointers (`slow = 6`, `med = 1`, `fast = null`).\n\n7. **Final Calculation:**\n - Since `max` is not `0`, set `arr[0]` to `min` and `arr[1]` to `max`.\n - Return `[1, 4]`.\n\n### Complexity Analysis\n\n- **Time Complexity:** O(n)\n - The code traverses the linked list once, performing constant-time operations for each node. Thus, the time complexity is linear in terms of the number of nodes (`n`).\n\n- **Space Complexity:** O(1)\n - The code uses a fixed amount of extra space for pointers and variables, resulting in constant space usage. Thus, the space complexity is constant.\n\n\n\n
4
0
['Linked List', 'C++', 'Java']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
💡 C++ | O(n) | Beats 99% | Simple Logic | With Full Explanation ✏️
c-on-beats-99-simple-logic-with-full-exp-b4kj
\n# Approach\n1. Traverse the Linked List: Convert the linked list to a vector of values for easier access.\n2. Identify Critical Points: Traverse the vector to
Tusharr2004
NORMAL
2024-07-05T03:07:35.536850+00:00
2024-07-05T03:08:46.248099+00:00
13
false
\n# Approach\n1. **Traverse the Linked List:** Convert the linked list to a vector of values for easier access.\n2. **Identify Critical Points:** Traverse the vector to find critical points, which are defined as nodes where the value is either greater than both its neighboring values or less than both its neighboring values.\n3. **Calculate Distances:** If there are fewer than two critical points, \nreturn \'{-1, -1}\'. Otherwise, calculate the minimum distance between consecutive critical points and the distance between the first and the last critical points.\n\n# Complexity\n- Time complexity:\n```O(n)```\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\n#pragma GCC optimize("Ofast")\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n // Optimizing input/output speed\n cin.tie(0);\n cout.tie(0);\n ios::sync_with_stdio(false);\n \n vector<int> crit; // To store indices of critical points\n vector<int> temp; // To store values of the linked list nodes\n \n // Converting linked list to a vector of values\n while (head != nullptr) {\n temp.push_back(head->val);\n head = head->next;\n }\n \n // Identifying critical points\n for (int i = 1; i < temp.size() - 1; ++i) {\n if ((temp[i] > temp[i - 1] && temp[i] > temp[i + 1]) ||\n (temp[i] < temp[i - 1] && temp[i] < temp[i + 1])) {\n crit.push_back(i + 1);\n }\n }\n \n // If there are fewer than 2 critical points, return {-1, -1}\n if (crit.size() < 2) {\n return {-1, -1};\n }\n \n // Calculating minimum distance between consecutive critical points\n int mini = crit[1] - crit[0];\n for (int i = 2; i < crit.size(); ++i) {\n if (crit[i] - crit[i - 1] < mini) {\n mini = crit[i] - crit[i - 1];\n }\n }\n \n // Return minimum distance and distance between first and last critical points\n return {mini, crit.back() - crit[0]};\n }\n};\n```\n\n\n\n![upvote.jpeg](https://assets.leetcode.com/users/images/3f696237-5498-43a7-97da-6c382b493755_1717388390.637768.jpeg)\n\n\n# Ask any doubt !!!\nMessage me on LinkedIn if you have any doubt related to this question \uD83D\uDE0A\uD83D\uDC47\n\uD83D\uDD17 https://www.linkedin.com/in/bhardwajtushar2004/\n\n# Connect with me on LinkedIn :)
4
0
['Linked List', 'C++']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
simple sol
simple-sol-by-abichal-webr
Intuition\nGo through the linked list and simply find the critical points. Compare these critical points to find the solution\n\n# Approach\nKeep a pointer for
abichal
NORMAL
2024-07-05T00:27:49.314564+00:00
2024-07-05T00:27:49.314588+00:00
225
false
# Intuition\nGo through the linked list and simply find the critical points. Compare these critical points to find the solution\n\n# Approach\nKeep a pointer for prev, curr and next to find the critical points. Add the position in an array and then calculate the minimum distance and the maximum distance.\n\n# Complexity\n- Time complexity:\nO(N)\n\n# Code\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:\n prev = head\n head = head.next\n critical_pos = []\n curr = 1\n mindis = sys.maxsize\n\n if(head.next==None):\n return [-1, -1]\n\n while(head.next!=None):\n nextel = head.next\n if(prev.val<head.val and nextel.val<head.val):\n critical_pos.append(curr)\n elif(prev.val>head.val and nextel.val>head.val):\n critical_pos.append(curr)\n\n if(len(critical_pos)>1):\n mindis = min(mindis, critical_pos[-1]-critical_pos[-2])\n curr+=1\n prev = head\n head = head.next\n\n if(len(critical_pos)<=1):\n return [-1, -1]\n\n answer = [mindis, critical_pos[-1]-critical_pos[0]]\n\n return answer\n```
4
0
['Python3']
1
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
[Python 3] 2 solutions: save all critical points, then calculate result or calculate distance on fly
python-3-2-solutions-save-all-critical-p-vhoz
python3 []\nclass Solution:\n def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:\n idx, i = [], 1\n prev, cur = head,
yourick
NORMAL
2023-07-26T16:19:54.520162+00:00
2024-07-05T00:49:59.888036+00:00
291
false
```python3 []\nclass Solution:\n def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:\n idx, i = [], 1\n prev, cur = head, head.next\n while cur and cur.next:\n if prev.val < cur.val > cur.next.val or prev.val > cur.val < cur.next.val:\n idx.append(i)\n prev = cur\n cur = cur.next\n i += 1\n\n if len(idx) < 2:\n return [-1, -1]\n \n minDist = min(j - i for i, j in pairwise(idx))\n maxDist = idx[-1] - idx[0]\n\n return [minDist, maxDist]\n\n```\n\n##### Without additional memory for saving all positions.\n```python3 []\nclass Solution:\n def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:\n prev, cur = head, head.next\n pos, firstPos, prevPos, minDist = 0, None, None, math.inf\n \n while cur.next:\n pos += 1\n if prev.val < cur.val > cur.next.val or prev.val > cur.val < cur.next.val:\n if prevPos:\n minDist = min(minDist, pos - prevPos)\n prevPos = pos\n else:\n firstPos = prevPos = pos\n \n cur, prev = cur.next, cur\n\n if minDist == math.inf:\n return [-1, -1]\n\n return [minDist, prevPos - firstPos]\n```
4
0
['Linked List', 'Python', 'Python3']
1
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
C++ Solution with Comments
c-solution-with-comments-by-abhi_vee-ga93
\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) \n { \n vector<int> v; // v to store critical point locatio
abhi_vee
NORMAL
2021-10-31T04:01:25.710809+00:00
2021-10-31T04:03:29.486131+00:00
296
false
```\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) \n { \n vector<int> v; // v to store critical point locations\n ListNode*prev = head; ListNode* curr = head->next; ListNode* ahead = head->next->next;\n int i=2;\n \n while(curr->next != NULL)\n {\n if(prev->val < curr->val && curr->val > ahead->val)\n v.push_back(i); // local maxima at i\n if(prev->val > curr->val && curr->val < ahead->val)\n v.push_back(i); // local minima at i\n prev = prev->next, curr = curr->next, ahead = ahead->next, i++;\n }\n \n if(v.size() < 2) \n return {-1,-1};\n \n int temp, min_dist = INT_MAX;\n for(int i=1; i<v.size(); i++) // minimum distance can be anywhere\n {\n temp = v[i] - v[i-1]; // check for every pair\n min_dist = min(temp, min_dist); // greedily get the minimum distance\n }\n \n return {min_dist, v[v.size()-1] - v[0]}; // maxmimum distance will be highest i - least i\n }\n};\n```\n\n**upvote if you like it**
4
0
['C', 'C++']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
99% Running time | Easy to understand
99-running-time-easy-to-understand-by-li-kv3k
Intuition\n Describe your first thoughts on how to solve this problem. \nCritical points in a linked list are nodes where the value is either a local maximum or
LinhNguyen310
NORMAL
2024-07-05T13:53:43.481109+00:00
2024-07-05T13:53:43.481149+00:00
6
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCritical points in a linked list are nodes where the value is either a local maximum or a local minimum. A local maximum is a node whose value is greater than its neighbors, and a local minimum is a node whose value is smaller than its neighbors. Once these critical points are identified, calculating the minimum and maximum distances between them involves simple arithmetic on their positions.\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nIdentify Critical Points:\n\nTraverse the linked list while keeping track of the current node, the previous node, and the next node.\nFor each node, check if it is a local maximum or minimum.\nRecord the positions (indices) of these critical points.\nCompute Distances:\n\nIf there are fewer than two critical points, return [-1, -1] as no meaningful distance can be calculated.\nOtherwise, compute the minimum and maximum distances between the identified critical points.\nDetailed Steps\nInitialize an empty list local to store the positions of the critical points.\nTraverse the linked list using a pointer, maintaining a reference to the previous node.\nFor each node, check if it is a local minimum or maximum and record its position if it is.\nAfter identifying all critical points, compute the minimum and maximum distances between them.\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(k)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution(object):\n def nodesBetweenCriticalPoints(self, head):\n """\n :type head: Optional[ListNode]\n :rtype: List[int]\n """\n ret = [-1, -1]\n\n local = []\n\n temp = head\n prev = temp\n i = 0\n while temp.next:\n nextNode = temp.next\n if (temp.val > prev.val and temp.val > nextNode.val) or (temp.val < prev.val and temp.val < nextNode.val):\n local.append(i) \n prev = temp\n temp = temp.next\n i += 1\n \n m = len(local)\n \n if m <= 1:\n return ret\n minGap = float("inf")\n maxGap = local[-1] - local[0]\n\n for i in range(1, m):\n prev = local[i - 1]\n curr = local[i]\n gap = curr - prev\n minGap = min(minGap, gap)\n\n return [minGap, maxGap]\n```\n\n![packied_spongebob.jpg](https://assets.leetcode.com/users/images/2af03932-0226-4da8-aff2-9f081da379db_1720187619.3815594.jpeg)\n
3
0
['Python']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
99% Running time | Easy to understand
99-running-time-easy-to-understand-by-li-kpjz
Intuition\n Describe your first thoughts on how to solve this problem. \nCritical points in a linked list are nodes where the value is either a local maximum or
LinhNguyen310
NORMAL
2024-07-05T13:53:42.593074+00:00
2024-07-05T13:53:42.593106+00:00
4
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCritical points in a linked list are nodes where the value is either a local maximum or a local minimum. A local maximum is a node whose value is greater than its neighbors, and a local minimum is a node whose value is smaller than its neighbors. Once these critical points are identified, calculating the minimum and maximum distances between them involves simple arithmetic on their positions.\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nIdentify Critical Points:\n\nTraverse the linked list while keeping track of the current node, the previous node, and the next node.\nFor each node, check if it is a local maximum or minimum.\nRecord the positions (indices) of these critical points.\nCompute Distances:\n\nIf there are fewer than two critical points, return [-1, -1] as no meaningful distance can be calculated.\nOtherwise, compute the minimum and maximum distances between the identified critical points.\nDetailed Steps\nInitialize an empty list local to store the positions of the critical points.\nTraverse the linked list using a pointer, maintaining a reference to the previous node.\nFor each node, check if it is a local minimum or maximum and record its position if it is.\nAfter identifying all critical points, compute the minimum and maximum distances between them.\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(k)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution(object):\n def nodesBetweenCriticalPoints(self, head):\n """\n :type head: Optional[ListNode]\n :rtype: List[int]\n """\n ret = [-1, -1]\n\n local = []\n\n temp = head\n prev = temp\n i = 0\n while temp.next:\n nextNode = temp.next\n if (temp.val > prev.val and temp.val > nextNode.val) or (temp.val < prev.val and temp.val < nextNode.val):\n local.append(i) \n prev = temp\n temp = temp.next\n i += 1\n \n m = len(local)\n \n if m <= 1:\n return ret\n minGap = float("inf")\n maxGap = local[-1] - local[0]\n\n for i in range(1, m):\n prev = local[i - 1]\n curr = local[i]\n gap = curr - prev\n minGap = min(minGap, gap)\n\n return [minGap, maxGap]\n```\n\n![packied_spongebob.jpg](https://assets.leetcode.com/users/images/2af03932-0226-4da8-aff2-9f081da379db_1720187619.3815594.jpeg)\n
3
0
['Python']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
C# Solution for Find the Minimum and Maximum Number of Nodes Between Critical Points Problem
c-solution-for-find-the-minimum-and-maxi-owyt
Intuition\n Describe your first thoughts on how to solve this problem. \nThe task is to find the minimum and maximum distances between critical points (local ma
Aman_Raj_Sinha
NORMAL
2024-07-05T12:02:10.373117+00:00
2024-07-05T12:02:10.373140+00:00
101
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe task is to find the minimum and maximum distances between critical points (local maxima or minima) in a linked list. The approach involves two main steps: first, identify and store the indices of all critical points, and second, compute the minimum and maximum distances between these indices.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1.\tInitial Check:\n\t\u2022\tIf the list has fewer than three nodes, it is impossible to have any critical points since a critical point requires both a previous and a next node.\n2.\tTraverse the List:\n\t\u2022\tInitialize pointers prev, curr, and next to traverse the list.\n\t\u2022\tFor each node, check if it is a critical point by comparing its value with prev and next.\n\t\u2022\tIf it is a critical point, add the current index to a list of critical points.\n3.\tCalculate Distances:\n\t\u2022\tIf there are fewer than two critical points, return [-1, -1] as there aren\u2019t enough points to calculate distances.\n\t\u2022\tTo find the minimum distance, iterate through the list of critical points and find the smallest difference between consecutive indices.\n\t\u2022\tThe maximum distance is the difference between the first and the last critical point in the list.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n): The solution involves two passes through the linked list:\n\t\u2022\tThe first pass is to identify and store the indices of the critical points.\n\t\u2022\tThe second pass is to calculate the minimum and maximum distances.\n\t\u2022\tBoth passes are linear with respect to the number of nodes, making the overall time complexity O(n).\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n): The space complexity is mainly due to the storage of the indices of critical points. In the worst case, every node except the first and last could be a critical point, resulting in space complexity proportional to the number of nodes.\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * public int val;\n * public ListNode next;\n * public ListNode(int val=0, ListNode next=null) {\n * this.val = val;\n * this.next = next;\n * }\n * }\n */\npublic class Solution {\n public int[] NodesBetweenCriticalPoints(ListNode head) {\n // If the list has fewer than 3 nodes, there can\'t be any critical points\n if (head == null || head.next == null || head.next.next == null) {\n return new int[] { -1, -1 };\n }\n\n List<int> criticalPoints = new List<int>();\n ListNode prev = head;\n ListNode curr = head.next;\n ListNode next = curr.next;\n int index = 1; // curr is the second node\n\n // Traverse the list to collect critical points\n while (next != null) {\n if ((curr.val > prev.val && curr.val > next.val) || (curr.val < prev.val && curr.val < next.val)) {\n criticalPoints.Add(index);\n }\n prev = curr;\n curr = next;\n next = next.next;\n index++;\n }\n\n // If there are fewer than 2 critical points, return [-1, -1]\n if (criticalPoints.Count < 2) {\n return new int[] { -1, -1 };\n }\n\n // Calculate the minimum and maximum distances between critical points\n int minDistance = int.MaxValue;\n int maxDistance = criticalPoints[criticalPoints.Count - 1] - criticalPoints[0];\n\n for (int i = 1; i < criticalPoints.Count; i++) {\n minDistance = Math.Min(minDistance, criticalPoints[i] - criticalPoints[i - 1]);\n }\n\n return new int[] { minDistance, maxDistance };\n }\n}\n```
3
0
['C#']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Easy One Pass Solution Explained✅🏆
easy-one-pass-solution-explained-by-_ris-ti6t
Nodes Between Critical Points\n\n## Problem Description\n\nGiven a singly linked list, we need to find the minimum and maximum distances between critical points
_Rishabh_96
NORMAL
2024-07-05T10:42:51.131086+00:00
2024-07-05T10:42:51.131137+00:00
69
false
# Nodes Between Critical Points\n\n## Problem Description\n\nGiven a singly linked list, we need to find the minimum and maximum distances between critical points in the list. A critical point in the list is defined as a node that is either a local minimum or a local maximum. A node is a local minimum if it is smaller than both the previous and the next node. Similarly, a node is a local maximum if it is greater than both the previous and the next node.\n\n## Approach\n\n1. **Traversal and Identification:**\n - Traverse the linked list with two pointers: `prev` (previous node) and `curr` (current node), starting from the first and second nodes, respectively.\n - Use an index `i` to keep track of the position of the current node.\n - For each node, check if it is a local minimum or maximum compared to its neighboring nodes.\n - If it is a critical point, record its index in the `criticalPoints` vector.\n\n2. **Distance Calculation:**\n - If there are fewer than 2 critical points, return `{-1, -1}` since no valid distances can be calculated.\n - Otherwise, calculate the minimum distance between consecutive critical points.\n - Calculate the maximum distance between the first and last critical points.\n - Return both the minimum and maximum distances.\n\n## Complexity\n\n- **Time complexity:** \\(O(n)\\)\n - We traverse the linked list once, making this approach linear in time complexity.\n- **Space complexity:** \\(O(k)\\)\n - The space complexity is \\(O(k)\\), where \\(k\\) is the number of critical points. In the worst case, this is \\(O(n)\\), but typically \\(k \\leq n\\).\n\n## Code\n\n```cpp\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\n\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n vector<int> criticalPoints;\n ListNode* prev = head;\n ListNode* curr = head->next;\n int i = 1;\n\n while (curr && curr->next) {\n if ((curr->val > prev->val && curr->val > curr->next->val) || \n (curr->val < prev->val && curr->val < curr->next->val)) {\n criticalPoints.push_back(i);\n }\n prev = curr;\n curr = curr->next;\n i++;\n }\n\n if (criticalPoints.size() < 2) {\n return {-1, -1};\n }\n\n int minDist = INT_MAX;\n for (int i = 1; i < criticalPoints.size(); ++i) {\n minDist = min(minDist, criticalPoints[i] - criticalPoints[i - 1]);\n }\n\n int maxDist = criticalPoints.back() - criticalPoints.front();\n\n return {minDist, maxDist};\n }\n};\n
3
0
['Linked List', 'C++']
1
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Single Pass Solution | Java | C++
single-pass-solution-java-c-by-lazy_pota-uuxw
Intuition,approach, and complexity discussed in video solution in detail\nhttps://youtu.be/Yq9W_ryX9OA\n# Code\nJava\n\nclass Solution {\n public int[] nodes
Lazy_Potato_
NORMAL
2024-07-05T06:54:13.860874+00:00
2024-07-05T06:54:13.860901+00:00
397
false
# Intuition,approach, and complexity discussed in video solution in detail\nhttps://youtu.be/Yq9W_ryX9OA\n# Code\nJava\n```\nclass Solution {\n public int[] nodesBetweenCriticalPoints(ListNode head) {\n int minDist = Integer.MAX_VALUE, maxDist = Integer.MIN_VALUE;\n ListNode prevNode = head;\n int currLoc = 0, minCriticLoc = Integer.MAX_VALUE, maxCriticLoc = Integer.MIN_VALUE;\n for(ListNode currNode = head; currNode != null; currNode = currNode.next){\n currLoc++;\n if(currLoc > 1 && currNode.next != null && ((currNode.next.val < currNode.val && prevNode.val < currNode.val) || ((currNode.next.val > currNode.val && prevNode.val > currNode.val)))){\n if(minCriticLoc != Integer.MAX_VALUE){\n minDist = Math.min(minDist, currLoc - maxCriticLoc);\n maxDist = Math.max(maxDist, currLoc - minCriticLoc);\n }\n if(minCriticLoc == Integer.MAX_VALUE){\n minCriticLoc = currLoc;\n }\n maxCriticLoc = currLoc;\n }\n prevNode = currNode;\n\n }\n return new int[]{(minDist == Integer.MAX_VALUE ? -1 : minDist), (maxDist == Integer.MIN_VALUE ? -1 : maxDist)};\n }\n}\n```\nC++\n```\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n int minDist = INT_MAX, maxDist = INT_MIN;\n ListNode* prevNode = head;\n int currLoc = 0, minCriticLoc = INT_MAX, maxCriticLoc = INT_MIN;\n for (ListNode* currNode = head; currNode != nullptr; currNode = currNode->next) {\n currLoc++;\n if (currLoc > 1 && currNode->next != nullptr &&\n ((currNode->next->val < currNode->val && prevNode->val < currNode->val) ||\n (currNode->next->val > currNode->val && prevNode->val > currNode->val))) {\n if (minCriticLoc != INT_MAX) {\n minDist = min(minDist, currLoc - maxCriticLoc);\n maxDist = max(maxDist, currLoc - minCriticLoc);\n }\n if (minCriticLoc == INT_MAX) {\n minCriticLoc = currLoc;\n }\n maxCriticLoc = currLoc;\n }\n prevNode = currNode;\n }\n return {minDist == INT_MAX ? -1 : minDist, maxDist == INT_MIN ? -1 : maxDist};\n }\n};\n```
3
0
['Linked List', 'C++', 'Java']
1
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
JavaScript Simple Solution, Beats 98% time complexity and 92% space complexity
javascript-simple-solution-beats-98-time-kjz3
Intuition\nThe code aims to find the minimum and maximum distances between critical points in a linked list. A critical point is defined as a node where the val
briancode99
NORMAL
2024-07-05T06:22:34.443002+00:00
2024-07-05T06:22:34.443037+00:00
33
false
# Intuition\nThe code aims to find the minimum and maximum distances between critical points in a linked list. A critical point is defined as a node where the value is strictly greater or strictly lesser than its immediate neighbors. My initial thought is that we need to traverse the linked list, identify these critical points, and keep track of the distances between them.\n\n# Approach\n1. Traverse the linked list: We need to iterate through the nodes of the linked list to identify the critical points.\n2. Identify critical points: We compare each node\'s value with its previous and next node\'s values. If the current node\'s value is either strictly greater or strictly lesser than both its neighbors, it is a critical point.\nTrack distances:\n3. We need to store the index of the first critical point we encounter (for calculating the maximum distance).\nWe also need to keep track of the minimum distance between critical points.\n4. Calculate minimum and maximum distances:\n- The minimum distance is simply the difference between the indices of the two most recently encountered critical points.\n- The maximum distance is the difference between the indices of the first and last critical points.\n5. Return results: If there are no critical points, we return [-1, -1]. Otherwise, we return the minimum and maximum distances calculated.\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @return {number[]}\n */\nvar nodesBetweenCriticalPoints = function (head) {\n if (!head) {\n return [-1, -1];\n }\n\n let minDistance = Infinity;\n let first;\n let last;\n\n let prev = null;\n let cur = head;\n let counter = 0;\n\n while (cur) {\n counter++;\n\n if (prev && cur.next) {\n if (\n (cur.val < prev.val && cur.val < cur.next.val) ||\n (cur.val > prev.val && cur.val > cur.next.val)\n ) {\n // store first critical point position\n if (!first) {\n first = counter;\n }\n\n // calculate the minimum distance\n if (last) {\n minDistance = Math.min(minDistance, counter - last);\n }\n\n // store last critical point position\n last = counter;\n }\n }\n\n prev = cur;\n cur = cur.next;\n }\n\n if (minDistance === Infinity) {\n return [-1, -1];\n }\n\n return [minDistance, last - first];\n};\n```
3
0
['JavaScript']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Traverse through the list and capture the indices, Easy to understand solution.
traverse-through-the-list-and-capture-th-que8
Intuition\nWe simply just need to find the indices of the local maxima and local minimas. Since the indexing here is starting from 1, We will keep that in mind
sxnchayyyy
NORMAL
2024-07-05T06:10:35.744247+00:00
2024-07-05T06:10:35.744282+00:00
244
false
# Intuition\nWe simply just need to find the indices of the local maxima and local minimas. Since the indexing here is starting from 1, We will keep that in mind and traverse through the array looking for asked maxima and minimas and we will store their indices as we move forward.\n\n# Approach\nTraverse through the linkedlist and keep a note of all the indices that have a local maxima or a local minima, Since we are traversing from the front to the back the indices we are going to find will be in a sorted order of increasing values, then we just have to check for the base case and return the maximum and minimum difference value of the found indices.\n\n# Complexity\n- Time complexity:\nO(n) A single traversal through the linkedlist and the array that we have used.\n\n- Space complexity:\nO(n) We are using a vector to store the indices of the asked values, please comment if there is a way to optimize the space complexity\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n vector<int> res;\n ListNode* prev=head;\n ListNode* curr=head->next;\n int ind=2;\n while(curr->next)\n {\n if(curr->val > prev->val && curr->val > curr->next->val)\n {\n res.push_back(ind);\n }\n else if(curr->val < prev->val && curr->val < curr->next->val)\n {\n res.push_back(ind);\n }\n prev=curr;\n curr=curr->next;\n ind++;\n }\n if(res.size()<2)\n {\n return {-1,-1};\n }\n int maxi=res.back()-res[0];\n int mini=INT_MAX;\n for(int i=1 ; i<res.size() ; i++)\n {\n mini=min(mini,res[i]-res[i-1]);\n }\n return {mini,maxi};\n }\n};\n```
3
0
['C++']
6
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Beginner-Friendly C++ Solution || Easy to Understand || T.C. O(n) || One Stop Solution.
beginner-friendly-c-solution-easy-to-und-l4qq
Intuition\nCritical points in a linked list are nodes where the value is either a local minimum or maximum. To find the minimum and maximum distances between cr
omkarsalunkhe3597
NORMAL
2024-07-05T04:48:49.764594+00:00
2024-07-05T04:48:49.764638+00:00
150
false
# Intuition\nCritical points in a linked list are nodes where the value is either a local minimum or maximum. To find the minimum and maximum distances between critical points, we need to identify and record their positions, then compute the required distances.\n\n# Approach\n1. Traverse the list with three pointers: `prev`, `curr`, and `nextnode` to check each triplet of nodes.\n2. Identify critical points where the value of `curr` is a local minimum or maximum.\n3. Record the positions of these critical points in a vector.\n4. If there are at least two critical points, calculate the maximum distance `(between the first and last critical points)` and the minimum distance `(between any two consecutive critical points)`.\n5. If there are fewer than two critical points, return {-1, -1}.\n\n# Complexity\n- Time complexity:\n The time complexity is $$O(n)$$, where $$n$$ is the number of nodes in the linked list. We traverse the list once to find critical points and once more to compute distances.\n\n\n- Space complexity:\n The space complexity is $$O(1)$$ for the pointers and variables, plus $$O(k)$$ for the critical points list, where $$k$$ is the number of critical points.\n\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n ListNode* prev=head;\n ListNode* curr=head->next;\n ListNode* nextnode=curr->next;\n\n vector<int>maximas;\n int i=1;\n while(nextnode!=NULL)\n {\n if((prev->val < curr->val && nextnode->val < curr->val) || (prev->val > curr->val && nextnode->val > curr->val))\n {\n maximas.push_back(i);\n }\n prev=curr;\n curr=nextnode;\n nextnode=curr->next;\n i++;\n }\n int n=maximas.size();\n\n if(n >= 2)\n {\n int maxdistance=maximas[n-1] - maximas[0];\n int mindistance=INT_MAX;\n for(int i=0;i<n-1;i++)\n {\n mindistance=min(mindistance,maximas[i+1] - maximas[i]);\n }\n return {mindistance,maxdistance};\n }\n else{\n return {-1,-1};\n }\n }\n};\n```\n## Please upvote the solution if you find it helpful\n
3
0
['Linked List', 'C++']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
{C++} O(1) Space, Single Pass, Beats 100%, Detailed Explanation.
c-o1-space-single-pass-beats-100-detaile-v6c9
What is the question asking for\u2753\n Describe your approach to solving the problem. \nWe need to find critical points in the linked list where the value of a
Ashmit_Mehta
NORMAL
2024-07-05T03:38:03.522233+00:00
2024-07-12T03:17:42.969628+00:00
72
false
## *What is the question asking for\u2753*\n<!-- Describe your approach to solving the problem. -->\nWe need to find **critical** points in the linked list where the value of a node is either:\n\n- **Greater** than its **previous** and **next** nodes (forming a peak).\n\n- **Less** than its **previous** and **next** nodes (forming a trough).\n\nAnd return the minimum and maximum distance between any 2 distinct critical points, where a local minima or a local maxima. If there are less than 2 critical points we return `[-1,-1]`.\n\n\n## Approach \u2705\n\n- Initialize `ans` vector of size `2` with values `-1` indicating no critical points found initially.\n\n- Check if the list has at least three nodes `(head->next->next)` to proceed; if not, return `ans` because if there exists only 2 nodes we cannot find any critical points.\n\n- Use three pointers `(prev, curr, next)` to traverse the list.\n\n- `prev` starts from `head`, `curr` starts from `head->next`, and `next` starts from `head->next->next`.\n\n- We start traversing the list and the conditions `(prev->val < curr->val && curr->val > next->val)` and `(prev->val > curr->val && curr->val < next->val)` ensure that curr is identified as a peak or trough respectively.\n\n- `count` keeps track of the **position** of the nodes.\n\n- `mind` keeps track of the **minimum distance** between consecutive critical points, and `maxd` tracks the **maximum distance**.\n\n- This is done by keeping track of the first critical point encountered `f` the last critical point encountered `l` along with the current critical point `count`.\n\n- Finally we check if we encountered atleast 2 critical points or not and then return `min. distance` and the `max. distance` through the `ans` vector.\n\n<br>\n\n```cpp\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n \n vector<int> ans(2,-1);\n if(!head->next->next) return ans;\n \n ListNode *next = head->next->next, *curr = head->next, *prev = head;\n int mind = INT_MAX, maxd = INT_MIN, f = 0, l = 0, count = 1;\n\n while(next){\n if((prev->val < curr->val && curr->val > next->val) || (prev->val > curr->val && curr->val < next->val)){\n if(f && !l) l = count, mind = count-f;\n else if(f && l) mind = min(mind,count-l), l = count;\n\n if(!f) f=count;\n else maxd = max(maxd,count-f);\n }\n \n count++;\n prev=curr;\n curr=next;\n next=next->next;\n }\n\n if(f && l) ans[0]=mind,ans[1]=maxd;\n\nreturn ans;\n }\n};\n```\n\n#### Complexity \u2B50\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n> #### *~ Please upvote if you found it helpful\u2764\uFE0F*\n\n<br>\n\n![image.png](https://assets.leetcode.com/users/images/77b3ddd0-28ac-4533-b231-34a4e2c6544a_1720149523.9946177.png)\n\n---\n
3
0
['Linked List', 'C++']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Java Simple Clean solution | with Detail Explanatin
java-simple-clean-solution-with-detail-e-xsnm
Approach\n Describe your approach to solving the problem. \nTo make it simple, we track:\n\n- first and last indexes of local min/max.\n- the value of the previ
Shree_Govind_Jee
NORMAL
2024-07-05T03:31:32.439784+00:00
2024-07-05T03:31:32.439813+00:00
239
false
# Approach\n<!-- Describe your approach to solving the problem. -->\nTo make it simple, we track:\n\n- first and last indexes of local **`min/max`**.\n- the value of the previous node **`prev`**.\n- smallest difference between two adjacent indices **`(current i - idx)`** as **`min_d`**.\n- The result is `new int[] {min_d, max_d}`\n\n# Complexity\n- Time complexity:$$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) {\n * this.val = val;\n * this.next = next;\n * }\n * }\n */\nclass Solution {\n public int[] nodesBetweenCriticalPoints(ListNode head) {\n int max_d = Integer.MAX_VALUE;\n int min_d = Integer.MAX_VALUE;\n\n int prev = head.val, idx = 0;\n int i = 0;\n while (head.next != null) {\n if ((prev < head.val && head.val > head.next.val) ||\n (prev > head.val && head.val < head.next.val)) {\n if (idx != 0) {\n min_d = Math.min(min_d, i - idx);\n }\n\n max_d = Math.min(max_d, i);\n idx = i;\n }\n\n prev = head.val; // assign the new previous value\n head = head.next; // move the current node\n i++; // move the current index node\n }\n\n // edge case\n if (min_d == Integer.MAX_VALUE) {\n return new int[] { -1, -1 };\n }\n max_d = idx - max_d;\n return new int[] { min_d, max_d };\n }\n}\n```
3
0
['Linked List', 'Math', 'Two Pointers', 'Doubly-Linked List', 'Java']
1
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Easy C++ Solution with video Explanation
easy-c-solution-with-video-explanation-b-nesz
Video Explanation\nhttps://youtu.be/s_4qH7ldP7A\n# Intuition\n Describe your first thoughts on how to solve this problem. \nThe task is to find critical points
prajaktakap00r
NORMAL
2024-07-05T00:48:01.524357+00:00
2024-07-05T00:48:01.524403+00:00
573
false
# Video Explanation\nhttps://youtu.be/s_4qH7ldP7A\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe task is to find critical points in a linked list and calculate the minimum and maximum distances between these points. Critical points are nodes that are either local maxima or local minima. A node is a local maxima if its value is greater than both its previous and next nodes. Similarly, a node is a local minima if its value is less than both its previous and next nodes.\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Identify Critical Points: Traverse the linked list and identify nodes that are either local maxima or local minima by comparing each node\'s value with its previous and next nodes. Store the indices of these critical points.\n2. Calculate Distances:\n- If there are fewer than two critical points, return [-1, -1].\n- Otherwise, calculate the minimum distance between any two consecutive critical points and the maximum distance between the first and last critical points in the list.\n\n\n# Complexity\n- Time complexity:$$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n vector<int>critical;\n ListNode* cur=head;\n ListNode* next=head->next;\n ListNode* prev=NULL;\n int index=0;\n while(next!=NULL){\n\n if((prev!=NULL && cur->val<prev->val && cur->val<next->val)||\n (prev!=NULL && cur->val>prev->val && cur->val>next->val)){\n critical.push_back(index);\n }\n prev=cur;\n cur=next;\n next=next->next;\n index++;\n }\n\n if(critical.size()<2) return {-1,-1};\n int maxDist=critical.back()-critical.front();\n int minDist=INT_MAX;\n\n for(int i=0;i<critical.size()-1;i++){\n minDist=min(minDist,critical[i+1]-critical[i]);\n }\n return {minDist,maxDist};\n\n }\n};\n```
3
0
['C++']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
90% TC and 87% SC easy python solution
90-tc-and-87-sc-easy-python-solution-by-x9tcc
\ndef nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:\n\tans = [float(\'inf\'), -float(\'inf\')]\n\tcurr = head.next\n\tprev = head\n\t
nitanshritulon
NORMAL
2022-09-03T07:51:53.195089+00:00
2022-09-03T07:51:53.195121+00:00
493
false
```\ndef nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:\n\tans = [float(\'inf\'), -float(\'inf\')]\n\tcurr = head.next\n\tprev = head\n\ti = 1\n\tpos = []\n\twhile(curr.next):\n\t\tif(prev.val < curr.val > curr.next.val):\n\t\t\tpos.append(i)\n\t\telif(prev.val > curr.val < curr.next.val):\n\t\t\tpos.append(i)\n\t\ti += 1\n\t\tprev, curr = curr, curr.next\n\tif(len(pos) < 2):\n\t\treturn -1, -1\n\tfor i in range(1, len(pos)):\n\t\tans[0] = min(ans[0], pos[i]-pos[i-1])\n\tans[1] = pos[-1]-pos[0]\n\treturn ans\n```
3
0
['Linked List', 'Python', 'Python3']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Java || Easy Beginner Solution
java-easy-beginner-solution-by-devansh28-1o0i
\nclass Solution {\n public int[] nodesBetweenCriticalPoints(ListNode head) {\n List<Integer> list = new ArrayList<>();\n while(head != null) {
devansh2805
NORMAL
2022-04-07T14:41:54.603992+00:00
2022-04-07T14:41:54.604044+00:00
157
false
```\nclass Solution {\n public int[] nodesBetweenCriticalPoints(ListNode head) {\n List<Integer> list = new ArrayList<>();\n while(head != null) {\n list.add(head.val);\n head = head.next;\n }\n if(list.size() <= 2) {\n return new int[]{-1, -1};\n }\n List<Integer> indices = new ArrayList<>();\n for(int i=1;i<list.size()-1;i++) {\n if(list.get(i) > list.get(i+1) && list.get(i) > list.get(i-1)) {\n indices.add(i);\n }\n if(list.get(i) < list.get(i+1) && list.get(i) < list.get(i-1)) {\n indices.add(i);\n }\n }\n if(indices.size() < 2) {\n return new int[]{-1, -1};\n }\n return new int[]{minDiff(indices), maxDiff(indices)};\n }\n \n public int minDiff(List<Integer> nums) {\n Collections.sort(nums);\n int diff = Integer.MAX_VALUE;\n for(int i=0; i<nums.size()-1;i++) {\n diff = Math.min(nums.get(i+1) - nums.get(i), diff);\n }\n return diff;\n }\n \n public int maxDiff(List<Integer> nums) {\n int min = nums.get(0);\n int max = nums.get(0);\n for (int i=1;i<nums.size();i++) {\n min = Math.min(min, nums.get(i));\n max = Math.max(max, nums.get(i));\n }\n return max - min;\n }\n}\n```
3
0
['Java']
1
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Solution in Java
solution-in-java-by-farizma-mzwh
class Solution {\n \n public int[] nodesBetweenCriticalPoints(ListNode head) {\n \n //int[] res = {-1, -1};\n int min = Integer.MAX_V
farizma
NORMAL
2021-11-02T02:01:07.819234+00:00
2021-11-02T02:01:07.819289+00:00
67
false
class Solution {\n \n public int[] nodesBetweenCriticalPoints(ListNode head) {\n \n //int[] res = {-1, -1};\n int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;\n int FirstCP_index = -1, LastCP_index = -1;\n \n int prev = head.val;\n head = head.next;\n int count = 2;\n \n while(head.next != null) {\n int next = getNext(head);\n \n // System.out.println("val "+head.val +" ;count "+count);\n // System.out.println("min "+ min +" ;max "+max);\n \n if(prev < head.val && next < head.val || prev > head.val && next > head.val) { \n // System.out.println("---- CP ---- "+head.val);\n \n if(FirstCP_index == -1) {\n FirstCP_index = count; \n }\n \n else if(LastCP_index == -1) {\n LastCP_index = count;\n min = count - FirstCP_index;\n max = count - FirstCP_index;\n }\n \n else {\n min = Math.min(min, count - LastCP_index);\n max = Math.max(max, count - FirstCP_index);\n LastCP_index = count;\n }\n \n }\n \n prev = head.val;\n head = head.next;\n count++;\n }\n \n if(FirstCP_index == -1 || LastCP_index == -1)\n return new int[]{-1, -1};\n \n return new int[]{min, max};\n }\n \n int getNext(ListNode node) {\n if(node.next == null) return -1;\n return node.next.val;\n }\n}
3
0
[]
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Python Easy Solution
python-easy-solution-by-rnyati2000-0ofh
\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\n
rnyati2000
NORMAL
2021-10-31T05:41:32.297346+00:00
2021-10-31T05:41:32.297378+00:00
248
false
```\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:\n l = []\n while head:\n x = head.val\n l.append(x)\n head = head.next\n\n l1 = []\n\n if len(l) < 3:\n return [-1, -1]\n\n for i in range(1, len(l) - 1):\n if l[i] > l[i - 1] and l[i] > l[i + 1]:\n l1.append(i)\n\n if l[i] < l[i - 1] and l[i] < l[i + 1]:\n l1.append(i)\n\n # print(l1)\n\n if len(l1) < 2 and len(l1) < 2:\n return [-1, -1]\n\n if len(l1) == 2 and len(l1) == 2:\n return [(l1[1] - l1[0]), (l1[-1] - l1[0])]\n\n if len(l1) == 2 and len(l1) < 2:\n return [-1, (l1[-1] - l1[0])]\n\n if len(l1) < 2 and len(l1) == 2:\n return [(l1[1] - l1[0]), -1]\n\n a = l1[-1] - l1[0]\n b = l1[1] - l1[0]\n for i in range(1, len(l1)):\n # print(i)\n # print(l1[i]-l1[i-1])\n b = min(b, l1[i] - l1[i - 1])\n\n return [b, a]\n```\nIf u understood the code then plz UPVOTE...thnx in adv
3
2
['Python']
3
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Easy || One pass || Fast || Java Solution
easy-one-pass-fast-java-solution-by-iamc-cszx
\nclass Solution {\n\n\n\n public int[] nodesBetweenCriticalPoints(ListNode head)\n {\n ListNode temp=head.next;\n int min1=-1;\n Lis
IAmCoderrr
NORMAL
2021-10-31T05:31:54.134365+00:00
2021-10-31T05:31:54.134401+00:00
263
false
`\nclass Solution {\n\n\n\n public int[] nodesBetweenCriticalPoints(ListNode head)\n {\n ListNode temp=head.next;\n int min1=-1;\n ListNode prev=head;\n int min=Integer.MAX_VALUE;\n int pre=-1;\n int i=1;\n while(temp.next!=null){\n if((prev.val>temp.val && temp.val<temp.next.val) || (prev.val<temp.val && temp.val>temp.next.val)){\n \n // System.out.println(i);\n if(pre!=-1){\n min=Math.min(min,i-pre);\n }\n \n pre=i;\n if(min1==-1) min1=i;\n }\n prev=temp;\n temp=temp.next;\n i++;\n }\n \n if(min1==-1 || pre==min1) return new int[]{-1,-1};\n else return new int[]{min,pre-min1};\n }\n}\n`
3
1
['Java']
1
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Very Easy Solution java with detailed explanation!!
very-easy-solution-java-with-detailed-ex-i1kl
Approach\n\n1. Initialization:\n\n- Track Critical Points:\n - Initialize variables firstindex and lastindex to track the indices of the first and last critica
Digvijay_Tadage
NORMAL
2024-09-02T17:25:13.464276+00:00
2024-09-02T17:25:13.464301+00:00
7
false
### Approach\n\n**1. Initialization:**\n\n- **Track Critical Points:**\n - Initialize variables `firstindex` and `lastindex` to track the indices of the first and last critical points found in the linked list.\n - Use `prevIdx` to store the index of the previous critical point encountered.\n\n- **Smallest Distance:**\n - Initialize `min` to `Integer.MAX_VALUE` to keep track of the smallest distance between any two critical points.\n\n- **Previous Node Tracking:**\n - Set up pointers for `prev` (previous node), `current` (current node), and `Next` (next node) to traverse the linked list.\n - `idx` is used to track the current index of the node being processed.\n\n**2. Traversal:**\n\n- **Starting from the Second Node:**\n - Begin the traversal from the second node in the linked list.\n\n- **Check for Critical Points:**\n - For each node, determine if it is a critical point by comparing its value with the values of its previous and next nodes.\n \n- **If a Node is a Critical Point:**\n - **First Critical Point:**\n - If `prevIdx` is `-1`, it means this is the first critical point encountered. Set `firstindex`, `lastindex`, and `prevIdx` to the current index.\n\n - **Subsequent Critical Points:**\n - Calculate the distance from the last critical point by subtracting `prevIdx` from the current index.\n - Update `min` if the calculated distance is smaller than the current `min`.\n - Update `prevIdx` and `lastindex` to the current index.\n \n - **Move to the Next Node:**\n - Advance `prev`, `current`, and `Next` to continue traversing the linked list.\n - Increment `idx` to reflect the current index.\n\n**3. Result Calculation:**\n\n- **Edge Case Handling:**\n - If no critical points are found or if there is only one critical point (i.e., `firstindex` equals `lastindex`), return `{-1, -1}` since no meaningful distance can be calculated.\n\n- **Return Final Result:**\n - If there are at least two critical points, return an array with:\n - `ans[0]`: The smallest distance between any two consecutive critical points (`min`).\n - `ans[1]`: The distance between the first and last critical points, calculated as `lastindex - firstindex`.\n# Complexity\n- Time complexity:\n100%\n\n- Space complexity:\n83%\n\n# Code\n```java []\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n \n public int[] nodesBetweenCriticalPoints(ListNode head) {\n if (head.next.next==null){\n int[] ans={-1,-1};\n return ans;\n\n }\n \n ListNode current=head;\n ListNode prev=head;\n ListNode Next=head.next;\n int idx=0;\n int k=0;\n int min=Integer.MAX_VALUE;\n int firstindex=-1;\n int lastindex=-1;\n int prevIdx=-1;\n \n while( Next!=null ){\n if((current.val>Next.val && current.val>prev.val) || (current.val<Next.val && \n current.val<prev.val)) {\n \n if(prevIdx==-1){\n prevIdx=idx;\n firstindex=idx;\n lastindex=idx;\n }\n else{\n int diff=idx- prevIdx;\n min=Math.min(min,diff);\n prevIdx=idx;\n lastindex=idx;\n \n }\n \n\n }\n \n \n prev=current;\n current=Next;\n Next=Next.next;\n \n idx++; \n }\n if(firstindex==lastindex){\n int[] ans={-1,-1};\n return ans; \n }\n int [] ans=new int[2];\n ans[0]=min;\n ans[1]=lastindex-firstindex;\n return ans;\n }\n}\n```
2
0
['Java']
1
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
C++ || Easy to understand approach for beginner
c-easy-to-understand-approach-for-beginn-6ejm
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
that_1guy__
NORMAL
2024-07-09T14:11:13.720670+00:00
2024-07-09T14:11:29.618645+00:00
4
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n int findmin(vector<int> &maxmin){\n int mini = INT_MAX;\n for(int i = 1;i<maxmin.size();i++){\n mini = min(mini , maxmin[i]-maxmin[i-1]);\n }\n return mini ;\n }\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n if(head==nullptr||head->next==nullptr||head->next->next==nullptr){\n return {-1,-1};\n }\n vector<int>maxmin;\n int count = 2;\n ListNode* pre = head;\n ListNode* cur = head->next ;\n ListNode* sc =cur ->next ;\n while(sc!=nullptr){\n if((cur->val>sc->val&&cur->val>pre->val) || (cur->val<sc->val&&cur->val<pre->val) ){\n maxmin.push_back(count);\n }\n pre = pre->next;\n cur= cur->next;\n sc=sc->next;\n count++;\n }\n if(maxmin.size()<=1){\n return {-1,-1};\n }\n int min = findmin(maxmin);\n return {min, maxmin[maxmin.size()-1]-maxmin[0]};\n\n }\n};\n```
2
0
['C++']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Simple C++ solution | Constant space | No extra memory needed for critical points
simple-c-solution-constant-space-no-extr-x71g
Intuition\nThe minimum difference between two critical points is difference between the last and second last point and the maximum difference is difference betw
saurabhdamle11
NORMAL
2024-07-05T21:16:24.842726+00:00
2024-07-05T21:16:24.842743+00:00
18
false
# Intuition\nThe minimum difference between two critical points is difference between the last and second last point and the maximum difference is difference between the first and the last critical point.\n\n# Approach\n1. Initialize three pointers: prev, current and forward.\n2. Store the index of first critical point.\n3. Traverse through the rest of the linked list and keep a track of the last two critical points.\n4. return the minimum and maximum difference.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n vector<int> ans = {-1,-1};\n ListNode* prev = head;\n ListNode* cur = head->next;\n ListNode* fwd = cur->next;\n bool isFirst = true;\n int first = 2;\n int curPos = 1; int prevPos = 1;int ptr = 2;int minDiff = INT_MAX;\n while(fwd){\n if((cur->val<fwd->val && cur->val<prev->val)|| (cur->val>fwd->val && cur->val>prev->val)){\n if(isFirst){first = ptr;isFirst=false;prevPos = ptr;curPos = ptr;}\n else{prevPos=curPos;curPos=ptr;minDiff = min(minDiff,(curPos-prevPos));}\n }\n cur=cur->next;\n fwd=fwd->next;\n prev=prev->next;\n ++ptr;\n }\n if(minDiff == INT_MAX || (curPos-first==0)){return ans;}\n ans[0] = minDiff;ans[1] = curPos-first;\n return ans;\n }\n};\n```\nPlease upvote if you found it useful!
2
0
['Linked List', 'C++']
2
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Beats ✅✅✅ 100% ✅✅✅ JAVA.
beats-100-java-by-saiswaroop1234-hy4m
Intuition\nBeats 100%. No need to store previous node value.\n\n# Approach\nTraverse through the loop only once if one critical point is found then search for a
SaiSwaroop1234
NORMAL
2024-07-05T17:34:55.155006+00:00
2024-07-05T17:34:55.155044+00:00
6
false
# Intuition\nBeats 100%. No need to store previous node value.\n\n# Approach\nTraverse through the loop only once if one critical point is found then search for another other wise return [-1,-1] and repeat it once again.\n\nNow if we have more than two critical points we need to store the first critical node position and the position of previous node.\n\nFor the every next critical point we should check the compare the the distances for minimum and also directly update the maximum distance.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public int[] nodesBetweenCriticalPoints(ListNode head) {\n ListNode n=head;\n int i=0;\n int i1=-1;\n int a[]={-1,-1};\n while(n.next.next!=null)\n {\n i++;\n if((n.next.val>n.val && n.next.val>n.next.next.val) || (n.next.val<n.val && n.next.val<n.next.next.val))\n {\n i1=i;\n n=n.next;\n break;\n }\n n=n.next;\n }\n if(i1==-1)\n {\n return a;\n }\n int i2=-1;\n while(n.next.next!=null)\n {\n i++;\n if((n.next.val>n.val && n.next.val>n.next.next.val) || (n.next.val<n.val && n.next.val<n.next.next.val))\n {\n i2=i;n=n.next;\n a[0]=i2-i1;\n a[1]=i2-i1;\n break;\n }n=n.next;\n }\n if(i2==-1)\n {\n return a;\n }\n while(n.next.next!=null)\n {\n i++;\n if((n.next.val>n.val && n.next.val>n.next.next.val) || (n.next.val<n.val && n.next.val<n.next.next.val))\n {\n a[0]=Math.min(a[0],i-i2);\n a[1]=i-i1;\n i2=i;\n }n=n.next;\n }\n return a;\n }\n}\n```
2
0
['Java']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
SC: O(1), TC: O(n) | One pass | Simple approach
sc-o1-tc-on-one-pass-simple-approach-by-fzeyp
Intuition\n Describe your first thoughts on how to solve this problem. \nThere is no requirement to store every critical point!\n\n# Approach\n Describe your ap
AnishDhomase
NORMAL
2024-07-05T17:13:10.897744+00:00
2024-07-05T17:16:54.319791+00:00
21
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThere is no requirement to store every critical point!\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. `isCriticalPoint` function checks critical point.\n\n2. Now, we go through the linked list once, from start to end. As we go, we\'re looking for these critical points.\n\n3. Every time we find a critical point, we do a few things:\n- If it\'s the first one we\'ve found, we mark its position.\n- If it\'s not the first, we calculate the distance from the last critical point we found. \n- We keep track of the smallest distance we\'ve seen.\n- We also update the position of the last critical point we\'ve seen.\n\n4. After we\'ve gone through the whole list, we know where the first and last critical points are. The distance between these is our `maximum` distance.\n\n5. If we didn\'t find at least two critical points, we return `[-1, -1]` as the question asks.\n6. Otherwise, we return the minimum distance between adjacent critical points and the maximum distance between any two critical points.\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\n bool isCriticalPoint(ListNode *curr, ListNode *prev){\n if(prev == NULL) return false;\n if(curr -> next == NULL) return false;\n if(prev->val < curr->val && curr->val > curr->next->val) return true;\n if(prev->val > curr->val && curr->val < curr->next->val) return true;\n return false;\n }\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n int firstCriticalPt = -1, lastCriticalPt = -1, ind = 0, prevCriticalPt = -1;\n int minDist = INT_MAX, maxDist;\n ListNode *prev = NULL, *curr = head;\n while(curr){\n if(isCriticalPoint(curr, prev)){\n if(prevCriticalPt != -1)\n minDist = min(ind - prevCriticalPt, minDist);\n prevCriticalPt = ind;\n if(firstCriticalPt == -1) firstCriticalPt = ind;\n else lastCriticalPt = ind;\n }\n prev = curr;\n curr = curr -> next;\n ind ++;\n }\n if(lastCriticalPt == -1) return {-1,-1};\n maxDist = lastCriticalPt - firstCriticalPt;\n return {minDist, maxDist};\n }\n};\n```
2
0
['C++']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
C++ Code for Beginners
c-code-for-beginners-by-manral_0203-4qc4
Intuition\n Describe your first thoughts on how to solve this problem. \nThe given code aims to find the minimum and maximum distances between critical points i
Manral_0203
NORMAL
2024-07-05T15:04:43.241043+00:00
2024-07-05T15:04:43.241077+00:00
94
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe given code aims to find the minimum and maximum distances between critical points in a singly-linked list. A critical point is defined as a node in the linked list where the node is either a local maximum or a local minimum. Here\'s a step-by-step explanation of the code:\n\n### Step-by-Step Explanation:\n\n1. **Initialization**:\n - A vector `v` is initialized to store the positions (1-based index) of the critical points.\n - A vector `re` is initialized to store the result.\n - `cnt` is initialized to 1 to keep track of the current node\'s position.\n - `last` is initialized to 100000 as a placeholder for the smallest distance between two critical points.\n - `lc` is declared to store the position of the last critical point found.\n - `ptr` is a pointer that starts at the second node of the linked list.\n - `ptr1` is a pointer that starts at the head of the linked list.\n\n2. **Edge Cases**:\n - If the linked list is empty or has only one node, the result is `[-1, -1]`.\n\n3. **Traversing the List**:\n - The code traverses the list starting from the second node (`ptr`), with `ptr1` always pointing to the previous node.\n - For each node, it checks if the node is a critical point:\n - A node is a local minimum if its value is smaller than both its previous (`ptr1->val`) and next node (`ptr->next->val`).\n - A node is a local maximum if its value is greater than both its previous and next node.\n\n4. **Storing Critical Points**:\n - If a critical point is found, its position (`cnt`) is stored in vector `v`.\n - If `last` is still 100000 (indicating it\'s the first critical point found), `lc` is updated to the current position and `last` is incremented by 10.\n - If it\'s not the first critical point, the distance between the current critical point and the last critical point is calculated, and `last` is updated to the minimum of the current `last` and this new distance. `lc` is updated to the current position.\n\n5. **Result Calculation**:\n - If fewer than two critical points are found, the result is `[-1, -1]`.\n - Otherwise, the result contains:\n - The minimum distance between any two critical points (`last`).\n - The distance between the first and last critical points found (`v[v.size() - 1] - v[0]`).\n\n6. **Return the Result**:\n - The result vector `re` is returned.\n\n### Code Analysis:\n- The code correctly identifies critical points and computes the required distances.\n- It includes edge cases to handle empty lists or lists with a single node.\n- It maintains efficient tracking of critical points using vectors and simple arithmetic operations.\n\n### Example Usage:\n\nConsider a linked list with values: `1 -> 3 -> 2 -> 4 -> 1 -> 5 -> 2`. The critical points are at positions `2 (3)`, `3 (2)`, and `6 (5)`:\n- The minimum distance between critical points is `1` (between positions `2` and `3`).\n- The maximum distance between the first and last critical points is `4` (between positions `2` and `6`).\n\nThe function would return `[1, 4]`.\n\n### Improvements:\n- Remove the debug `cout` statements, as they are unnecessary for the final implementation.\n- Ensure proper initialization and edge case handling to avoid potential issues.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe given code attempts to solve the problem of finding the minimum and maximum distances between critical points in a singly linked list. Let\'s break down the approach and steps used in the code.\n\n### Approach:\n\n1. **Edge Case Handling**:\n - If the linked list is empty or contains only one node, return `[-1, -1]` as there are no critical points.\n\n2. **Initialization**:\n - Initialize a vector `v` to store positions of critical points.\n - Initialize a vector `re` to store the result.\n - Initialize `cnt` to 1 to keep track of the current node\'s position.\n - Initialize `last` to a large number (100000) as a placeholder for the minimum distance between two critical points.\n - Declare `lc` to store the position of the last critical point found.\n - Initialize pointers `ptr` to the second node and `ptr1` to the first node.\n\n3. **Traverse the List**:\n - Iterate through the linked list using `ptr` and `ptr1`.\n - For each node, check if it is a critical point:\n - A node is a local minimum if its value is smaller than both its previous (`ptr1->val`) and next node (`ptr->next->val`).\n - A node is a local maximum if its value is greater than both its previous and next node.\n - If a critical point is found, store its position (`cnt`) in vector `v`.\n\n4. **Update Minimum Distance**:\n - If it\'s the first critical point found, update `lc` to the current position.\n - If it\'s not the first critical point, calculate the distance between the current critical point and the last critical point, update `last` to the minimum of the current `last` and this new distance, and update `lc` to the current position.\n\n5. **Result Calculation**:\n - If fewer than two critical points are found, return `[-1, -1]`.\n - Otherwise, return the minimum distance between any two critical points (`last`) and the distance between the first and last critical points (`v[v.size() - 1] - v[0]`).\n\n6. **Return the Result**:\n - The result vector `re` is returned.\n\n### Summary:\n\n- **Critical Points**: Nodes that are either local minima or maxima.\n- **Edge Cases**: Handle empty or single-node linked lists.\n- **Traversal**: Traverse the list to identify and store positions of critical points.\n- **Distance Calculation**: Compute the minimum distance between consecutive critical points and the distance between the first and last critical points.\n- **Result**: Return the calculated distances or `[-1, -1]` if there are fewer than two critical points.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe complexity analysis of the given code involves determining both time complexity and space complexity.\n\n### Time Complexity:\n\n1. **Initialization**:\n - Initializing variables and vectors takes constant time, \\(O(1)\\).\n\n2. **Edge Case Check**:\n - Checking if the list is empty or has only one node is \\(O(1)\\).\n\n3. **Traversal**:\n - The main while loop traverses the linked list from the second node to the end. This loop runs \\(O(n)\\) times, where \\(n\\) is the number of nodes in the linked list.\n - Inside the loop, the code checks whether the current node is a critical point and updates the vector `v` and variables `last` and `lc` accordingly. These operations are \\(O(1)\\) for each node.\n\n4. **Result Calculation**:\n - After traversing the list, checking the size of vector `v` and computing the final result involves operations that take \\(O(1)\\) time.\n\nSince the traversal of the list dominates the time complexity, the overall time complexity of the function is \\(O(n)\\).\n\n### Space Complexity:\n\n1. **Auxiliary Space**:\n - The space used by the vector `v` depends on the number of critical points found. In the worst case, if every node is a critical point, the size of `v` is \\(O(n)\\).\n - The result vector `re` has a fixed size of 2, so its space usage is \\(O(1)\\).\n\n2. **Variables**:\n - Other variables (`cnt`, `last`, `lc`, `ptr`, `ptr1`) use a constant amount of space, \\(O(1)\\).\n\nTherefore, the overall space complexity of the function is \\(O(n)\\) in the worst case, where \\(n\\) is the number of nodes in the linked list.\n\n### Summary:\n\n- **Time Complexity**: \\(O(n)\\)\n- **Space Complexity**: \\(O(n)\\) in the worst case due to the vector `v` storing critical points.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n vector<int> v, re;\n int cnt = 1;\n if (head == NULL || head->next == NULL) {\n v.push_back(-1);\n v.push_back(-1);\n return v;\n }\n int last = 100000, lc;\n ListNode *ptr = head->next, *ptr1 = head;\n while (ptr->next != NULL) {\n if ((ptr1->val) > (ptr->val) && (ptr->val) < ptr->next->val) {\n v.push_back(cnt);\n if (last == 100000) {\n cout << cnt << endl;\n // last=cnt;\n last += 10;\n lc = cnt;\n } else {\n cout << cnt - lc << endl;\n last = min(last, cnt - lc);\n lc = cnt;\n }\n } else if ((ptr1->val) < (ptr->val) &&\n (ptr->val) > (ptr->next->val)) {\n v.push_back(cnt);\n if (last == 100000) {\n cout << cnt << endl;\n // last=cnt;\n last += 10;\n lc = cnt;\n } else {\n cout << cnt - lc << endl;\n last = min(last, cnt - lc);\n lc = cnt;\n }\n }\n cnt++;\n ptr = ptr->next;\n ptr1 = ptr1->next;\n }\n\n if (v.size() < 2) {\n re.push_back(-1);\n re.push_back(-1);\n } else {\n re.push_back(last);\n re.push_back(v[v.size() - 1] - v[0]);\n }\n return re;\n }\n};\n```
2
0
['Linked List', 'C++']
1
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Extremely Intuitive 🔥 Intuitive C++ Approach 🔥🔥
extremely-intuitive-intuitive-c-approach-tntm
Intuition\nWe need to find elements n which satisfy either of the conditions:\n\ni. current node has value greater than both, previous and next node\nii. curren
peakfor
NORMAL
2024-07-05T11:08:29.870792+00:00
2024-07-05T11:08:29.870834+00:00
0
false
# Intuition\nWe need to find elements n which satisfy either of the conditions:\n\ni. current node has value greater than both, previous and next node\nii. current node has value lesser than both, previous and next node\n\n# Approach\n1) use \'size\' variable to keep track of size of the linked list\n2) \'maxidx\' to store maximum distance, similarly \'minidx\' to store minimum distance\n3) Whenever we meet an element which satisfies the above 2 conditions, we store its index:\n\n if it is the first time we are seeing such an element, store it in \'firstidx\'\n if we already have a maxidx value, we now proceed to find the minidx value (condition if(maxidx!=0))\n\n4) If maxidx or minidx is still intiial value, it means we havent found 2 such nodes, so we return {-1,-1}\n5) Otherwise, return {minidx,maxidx}\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n ListNode* temp=head->next;\n ListNode* prev=head;\n int firstidx=0, previdx=0, maxidx=INT_MIN, minidx=INT_MAX;\n int size=1;\n\n while(temp->next!=nullptr){\n size++;\n if((temp->val>prev->val && temp->val>temp->next->val)||(temp->val<prev->val&&temp->val<temp->next->val)){\n if(firstidx==0)firstidx=size;\n maxidx=max(maxidx,size-firstidx);\n if(maxidx!=0)minidx=min(minidx, size-previdx);\n }\n prev=temp;\n temp=temp->next;\n }\n if(maxidx==INT_MIN)return {-1,-1};\n return {minidx,maxidx};\n }\n};\n```
2
0
['C++']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Python | Single Pass Traversal
python-single-pass-traversal-by-khosiyat-uacs
see the Successfully Accepted Submission\n\n# Code\n\nclass Solution:\n def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:\n
Khosiyat
NORMAL
2024-07-05T08:59:25.862941+00:00
2024-07-05T08:59:25.862965+00:00
218
false
[see the Successfully Accepted Submission](https://leetcode.com/problems/find-the-minimum-and-maximum-number-of-nodes-between-critical-points/submissions/1310271690/?envType=daily-question&envId=2024-07-05)\n\n# Code\n```\nclass Solution:\n def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:\n if not head or not head.next or not head.next.next:\n return [-1, -1]\n \n # To store positions of critical points\n critical_positions = []\n \n # Previous, current, and next nodes to identify critical points\n prev = head\n curr = head.next\n pos = 1 # Start with the position of the second node\n \n while curr.next:\n next_node = curr.next\n if (curr.val > prev.val and curr.val > next_node.val) or (curr.val < prev.val and curr.val < next_node.val):\n critical_positions.append(pos)\n \n prev = curr\n curr = next_node\n pos += 1\n \n # If fewer than two critical points, return [-1, -1]\n if len(critical_positions) < 2:\n return [-1, -1]\n \n # Calculate the minimum and maximum distances\n min_distance = float(\'inf\')\n max_distance = critical_positions[-1] - critical_positions[0]\n \n for i in range(1, len(critical_positions)):\n min_distance = min(min_distance, critical_positions[i] - critical_positions[i - 1])\n \n return [min_distance, max_distance]\n \n```\n\n\n# Steps\n\n## Define Critical Points\nA critical point is a local maxima or minima. This means a node is a critical point if:\n- It\'s greater than both its previous and next nodes (local maxima).\n- It\'s smaller than both its previous and next nodes (local minima).\n\n## Traverse the Linked List\nAs we traverse the linked list, we need to:\n- Keep track of the positions of critical points.\n- Maintain a list to store these positions.\n\n## Calculate Distances\n- If there are fewer than two critical points, return `[-1, -1]`.\n- Otherwise, compute the minimum and maximum distances between the stored positions.\n\n# Explanation of the Code\n\n## Initialization\n- We initialize `prev` to the head and `curr` to the second node.\n- We also start tracking positions from the second node (position 1).\n\n## Traversal and Identification\n- As we traverse the list, we check if `curr` is a critical point by comparing it with its previous and next nodes.\n- If it\'s a critical point, we store its position in `critical_positions`.\n\n## Distance Calculation\n- After collecting all critical positions, we check if there are fewer than two critical points.\n - If so, we return `[-1, -1]`.\n - Otherwise, we compute the minimum distance between consecutive critical points and the maximum distance between the first and the last critical points.\n\n\n![image](https://assets.leetcode.com/users/images/b1e4af48-4da1-486c-bc97-b11ae02febd0_1696186577.992237.jpeg)
2
0
['Python3']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
✅💯🔥Explanations No One Will Give You🎓🧠Detailed Approach🎯🔥Extremely Simple And Effective🔥
explanations-no-one-will-give-youdetaile-w94u
Intuition\nWe just want to get all the critical point\'s index of linked list.\nAs we got their index , we will find out the minimum difference and maximum diff
madhurpratap7355
NORMAL
2024-07-05T08:38:45.074319+00:00
2024-07-05T08:47:23.528449+00:00
23
false
# Intuition\nWe just want to get all the critical point\'s index of linked list.\nAs we got their index , we will find out the minimum difference and maximum difference between them .\n\n# Approach\n**Case 1:** if nodes count <=2 return {-1,-1}\n\n---\n**Case 2:** we will use three pointer which will point to first second and third node as (initially)\n\n**STEP 1:**\nprev=head(1st node)\ncurr=head->next(2nd node)\nfrwd=head->next->next(3rd node)\n\n**Step 2:**\nMake a count which give index of curr as we have check its value and initially count=1 because count is at index 1;\n\nNow, we will traverse in linked list till our frwd!=NULL\n(because we need to check only till second last node )\n\n**Step 3:**\nAlso initialise a vector<int>criPoints before to store all critical Points you get by\n 1. curr->val > prev->val && curr->val > frwd->val \n (says curr is **local maxima**)\n 2. curr->val < prev->val && curr->val < frwd->val \n (says curr is **local minima**)\n\nWhen we get critical points by these condition store there index in our cricPoints vector\n\n---\n**Step 4:**\nAfter iteration if our cricPoints size is less than 2 means it get one or less critical points [2->3->4->2] or[2->3->3->2] . than it will give result out as{-1,-1};\n\nIf size of criPoints is more than 2 \nWe will find maximum diffrence by getting difference of last and first node as a\nwe will find minimum by iterating in vector and takes the minimum of two as b\n\n **So in the end we return {b,a};**\n\n\n\n# Complexity\n- Time complexity:\no(N)\n\n- Space complexity:\no(cricPoints.size())\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n int findmin(vector<int> &criPoints){\n int mini=INT_MAX;\n for(int i=1;i<criPoints.size();i++){\n int diff=criPoints[i]-criPoints[i-1];\n mini=min(mini,diff);\n }\n return mini;\n }\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n if(head->next->next==NULL)return{-1,-1};\n vector<int>criPoints;\n ListNode* curr=head->next;\n ListNode* prev=head;\n ListNode* frwd=head->next->next;\n int count=1;\n while(frwd!=NULL){\n if((curr->val > prev->val && curr->val > frwd->val ) || (curr->val < prev->val && curr->val < frwd->val )){\n criPoints.push_back(count);\n }\n count++;\n prev=curr;\n curr=frwd;\n frwd=frwd->next;\n }\n int n=criPoints.size();\n if(n<2)return{-1,-1};\n \n int a=criPoints[n-1]-criPoints[0];\n int b=findmin(criPoints);\n\n return {b,a};\n }\n};\n```
2
0
['Linked List', 'Two Pointers', 'C++']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
✅ Easy C++ Solution
easy-c-solution-by-moheat-b1cz
Code\n\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\
moheat
NORMAL
2024-07-05T08:36:02.883850+00:00
2024-07-05T08:36:02.883880+00:00
101
false
# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\n bool criticalPoint(ListNode* prev, ListNode* curr, ListNode* next)\n {\n if(prev == NULL || curr == NULL || next == NULL)\n {\n return false;\n }\n if((prev-> val < curr-> val && curr-> val > next-> val) || (prev-> val > curr-> val && curr-> val < next-> val))\n {\n return true;\n }\n return false;\n }\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n vector<int> v = {-1,-1};\n vector<int> index;\n\n if(head-> next == NULL || head == NULL || head-> next-> next == NULL)\n {\n return {-1,-1};\n }\n\n ListNode* prev = NULL;\n ListNode* curr = head;\n ListNode* next = head-> next;\n int i = 1;\n\n while(next != NULL)\n {\n bool check = criticalPoint(prev,curr,next);\n if(check)\n {\n index.push_back(i);\n }\n prev = curr;\n curr = next;\n next = next-> next;\n i++;\n }\n\n if(index.size() < 2)\n {\n return v;\n }\n\n int minDis = INT_MAX;\n int maxDis = index.back() - index.front();\n int n = index.size();\n\n for(int i=1;i<n;i++)\n {\n minDis = min(minDis, index[i] - index[i-1]);\n }\n\n v[0] = minDis;\n v[1] = maxDis;\n\n return v;\n }\n};\n```
2
0
['C++']
1
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
EASY || BEGINNER || SIMULATE AS IT IS.
easy-beginner-simulate-as-it-is-by-abhis-7sjr
Hey fellas,This code defines a function nodesBetweenCriticalPoints(ListNode head) that takes the head of a linked list and returns an array containing two integ
Abhishekkant135
NORMAL
2024-07-05T08:08:31.416752+00:00
2024-07-05T08:08:31.416776+00:00
76
false
Hey fellas,This code defines a function `nodesBetweenCriticalPoints(ListNode head)` that takes the head of a linked list and returns an array containing two integers:\n\n- Minimum distance between any two critical points (local maxima or minima) in the linked list.\n- Maximum distance between any two critical points.\n\n**Explanation:**\n\n1. **Handling Base Cases:**\n - `if (head.next.next == null) { ... }`: Checks if the linked list has less than 3 nodes. If so, there can\'t be any critical points, and the function returns `[-1, -1]` to indicate this.\n\n2. **Iterating Through the Linked List:**\n - `int index = 1`: Initializes an index variable `index` to keep track of the node position (starting from 1 as the first two nodes are skipped).\n - `ListNode prev = head; ListNode curr = head.next; ListNode fwd = head.next.next;`: Initializes three pointers:\n - `prev`: Points to the previous node.\n - `curr`: Points to the current node.\n - `fwd`: Points to the node after the current node.\n - `while (fwd != null) { ... }`: The loop iterates while `fwd` (pointer to the next-next node) is not null, meaning there are at least 3 nodes remaining.\n\n3. **Identifying Critical Points:**\n - Inside the loop, the code checks for critical points (local maxima or minima) using the values of `prev`, `curr`, and `fwd`:\n - `if (prev.val > curr.val && fwd.val > curr.val) { ... }`: This condition identifies a local **minimum**. It checks if both `prev` and `fwd` have values greater than `curr`, indicating a dip in the sequence. If true, the current index (`index`) is added to the `al` list.\n - `else if (prev.val < curr.val && fwd.val < curr.val) { ... }`: This condition identifies a local **maximum**. It checks if both `prev` and `fwd` have values smaller than `curr`, indicating a peak in the sequence. If true, the current index (`index`) is added to the `al` list.\n - After checking for critical points, all three pointers (`prev`, `curr`, and `fwd`) are advanced to the next nodes for the next iteration.\n\n4. **Handling No Critical Points:**\n - `if (al.size() < 2) { ... }`: After the loop, the code checks if the `al` list (storing critical point indices) has less than 2 elements. This means no critical points were found, and the function returns `[-1, -1]`.\n\n5. **Calculating Minimum and Maximum Distances:**\n - `int min = Integer.MAX_VALUE;`: Initializes a variable `min` to store the minimum distance between critical points, set to the maximum integer value initially.\n - `for (int i = 1; i < al.size(); i++) { ... }`: This loop iterates through the `al` list (starting from the second element) to calculate the distances between critical points.\n - `min = Math.min(min, al.get(i) - al.get(i - 1));`: For each pair of consecutive critical point indices in `al`, the distance (current index - previous index) is calculated and compared with the current `min`. The smaller value is stored in `min` to keep track of the minimum distance.\n - `int[] ans = new int[2];`: Creates an integer array `ans` of size 2 to store the results.\n\n6. **Building the Result Array:**\n - `ans[0] = min;`: Assigns the minimum distance calculated previously to the first element of `ans`.\n - `ans[1] = al.get(al.size() - 1) - al.get(0);`: Calculates the maximum distance by subtracting the index of the first critical point from the index of the last critical point in `al`. This represents the overall span between the two furthest critical points.\n - `return ans;`: Returns the `ans` array containing the minimum and maximum distances between critical points.\n\n**Overall Functionality:**\n\n- The code iterates through the linked list, identifying critical points (local maxima/minima) based on the node values.\n- It stores the indices of critical points in a list.\n- If critical points are found, the code calculates the minimum and maximum distances between them and returns the results in an array.\n- If no critical points exist, the function indicates this by returning `[-1, -1]`.\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public int[] nodesBetweenCriticalPoints(ListNode head) {\n List<Integer> al=new ArrayList<>();\n if(head.next.next==null ){\n int [] ans={-1,-1};\n return ans;\n }\n int index=1;\n ListNode prev=head;\n ListNode curr=head.next;\n ListNode fwd=head.next.next;\n \n while(fwd!=null){\n if(prev.val>curr.val && fwd.val>curr.val){\n al.add(index);\n }\n else if(prev.val<curr.val && fwd.val<curr.val){\n al.add(index);\n }\n prev=prev.next;\n curr=curr.next;\n fwd=fwd.next;\n index++;\n }\n if(al.size()<2){\n int [] ans={-1,-1};\n return ans;\n }\n int min=Integer.MAX_VALUE;\n for(int i=1;i<al.size();i++){\n min=Math.min(min,al.get(i)-al.get(i-1));\n }\n int [] ans=new int [2];\n ans[0]=min;\n ans[1]=al.get(al.size()-1)-al.get(0);\n return ans;\n }\n}\n```
2
0
['Linked List', 'Java']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
O(1) Space, Straightforward
o1-space-straightforward-by-suthiwat-osqu
Approach\nTraverse through linked list while keeping track of prev, prev_i, first_i where\n- prev is a value of previous list node\n- prev_i is an index of prev
suthiwat
NORMAL
2024-07-05T07:44:06.911357+00:00
2024-07-05T07:44:06.911380+00:00
24
false
# Approach\nTraverse through linked list while keeping track of `prev`, `prev_i`, `first_i` where\n- `prev` is a value of previous list node\n- `prev_i` is an index of previous critical node\n- `first_i` is an index of first critical node\n\n`prev` will be use to determine if the current node is a critical or not. When we find a critical we will then calculate min distance as well and keep in `min_distance`. Note that we can only acheive min distance if there is a previous critical (`prev_i != -1`). Finally, we obtain `max_distance` from `prev_i - first_i`\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n int i = 0;\n int prev = -1; // value of previous list node\n int prev_i = -1; // index of previous critical node\n int first_i = -1; // index of first critical node\n int min_distance = INT_MAX;\n\n while (head) {\n if (prev != -1 && head->next != NULL) {\n if ((head->val < prev && head->val < head->next->val) || (head->val > prev && head->val > head->next->val)) {\n if (first_i == - 1) first_i = i;\n if (prev_i != -1) {\n min_distance = min(i - prev_i, min_distance);\n }\n prev_i = i;\n }\n }\n prev = head->val;\n head = head->next;\n i++;\n }\n \n if (prev_i == -1 || min_distance == INT_MAX) return { -1, -1};\n return { min_distance, prev_i - first_i };\n }\n};\n```
2
0
['C++']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Easy C++ Solution || Efficient 2 Pointers Approach || Beats 98%
easy-c-solution-efficient-2-pointers-app-wtw7
\n\n\n# Approach\n Describe your approach to solving the problem. \nUsing Two pointer to update the max and min distance.\n\n# Complexity\n- Time complexity: O(
DecafCoder0312
NORMAL
2024-07-05T07:40:14.894058+00:00
2024-07-05T07:40:14.894083+00:00
59
false
![image.png](https://assets.leetcode.com/users/images/c0d3108f-11cb-476f-a8d6-f2e3945d7e06_1720165144.338982.png)\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUsing Two pointer to update the max and min distance.\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n ListNode* ptr = head;\n ListNode* prev = NULL;\n int pr = 0;\n int cu = 0;\n int count = 1;\n vector<int> ans(2, -1);\n\n while (ptr) {\n prev = ptr;\n ptr = ptr->next;\n count++;\n if (ptr && ptr->next) {\n int ptrVal = ptr->val;\n int prevVal = prev->val;\n int nextVal = ptr->next->val;\n if ((ptrVal > prevVal && ptrVal > nextVal) || (ptrVal < prevVal && ptrVal < nextVal)) {\n pr = cu;\n cu = count;\n if (pr) {\n if (ans[0] != -1)\n ans[0] = min(ans[0], cu - pr);\n else\n ans[0] = cu - pr;\n if (ans[1] != -1)\n ans[1] += cu - pr;\n else\n ans[1] = cu - pr;\n }\n }\n }\n }\n\n return ans;\n }\n};\n```
2
0
['Linked List', 'Two Pointers', 'C++']
2
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
🚀🚀Single Iteration & O(1) Space Code C++🔥🔥💯
single-iteration-o1-space-code-c-by-syed-9h3z
Code\n\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\
Syed_Affan
NORMAL
2024-07-05T07:06:36.197707+00:00
2024-07-05T07:06:36.197743+00:00
54
false
# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n //Function to check whether this is a Critical point ?\n bool isCp(int p, int c, int n){\n if(c>p && c>n)return 1;\n if(c<p && c<n)return 1;\n return 0;\n }\n //Actual function\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n vector<int>ans(2,-1);\n\n\n ListNode* curr = head->next;\n ListNode* prev = head;\n ListNode* next = head->next->next;\n \n //Finding postion of 1st most Critical Point (1 based indexing)\n // Since the 1st most Node can never be C.P. Therefore \'2\'\n int pos1 = 2;\n\n //iterate untill we have \'next\' Node exist to Check for C.P.\n while(next){\n if(isCp(prev->val, curr->val, next->val)){\n //Found the 1st mode C.P. exit Loop\n break;\n }\n pos1++;\n prev = curr;\n curr = next;\n next = next->next;\n }\n\n //No Critical Point\n if(next==NULL)return ans;\n\n //Updating pointers to Check for Others C.P.\n\n //Updatig these pointers will prevent again Considering 1st C.P.\n prev = curr;\n curr = next;\n next = next->next;\n\n int ansmin = INT_MAX;\n\n int posPrev = pos1;\n int posCurr = pos1+1;\n\n while(next){\n if(isCp(prev->val, curr->val, next->val)){\n ansmin = min(ansmin, posCurr-posPrev);\n posPrev = posCurr;\n }\n posCurr++;\n prev = curr;\n curr = next;\n next = next->next;\n }\n\n //2nd Critical Point dosen\'t exist\n if(posPrev == pos1)return ans;\n\n //2nd Point exist\n\n ans[0] = ansmin;\n ans[1] = posPrev-pos1;\n return ans;\n }\n};\n\n```\n# Note: Please Don\'t Forget to Dry Run TO brush your Pointers Concpet.\n\n# \uD83D\uDC47\uD83D\uDC47 Also a single Upvote \uD83D\uDE0A\n![upv2.jpeg](https://assets.leetcode.com/users/images/07798f0d-9b57-49c2-88f4-b6754dd47145_1720163148.0275128.jpeg)\n\n
2
0
['C++']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
[C | C++] -> Solution
c-c-solution-by-zhanghx04-jjgj
Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(n)\n Add your space complexity here, e.g. O(n) \n\n# Co
zhanghx04
NORMAL
2024-07-05T06:41:31.609381+00:00
2024-07-05T06:43:49.499527+00:00
8
false
# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```C []\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * struct ListNode *next;\n * };\n */\n/**\n * Note: The returned array must be malloced, assume caller calls free().\n */\nint* nodesBetweenCriticalPoints(struct ListNode* head, int* returnSize) {\n int *result = (int *)malloc(2 * sizeof(int));\n if (result == NULL) {\n return NULL;\n }\n *returnSize = 2;\n result[0] = -1;\n result[1] = -1;\n\n if (head == NULL) {\n return result;\n }\n\n // Get critical points\' indexes\n int *critical_indexes = (int *)malloc(1e5 * sizeof(int));\n if (critical_indexes == NULL) {\n free(result);\n return NULL;\n }\n\n int critical_index_num = 0;\n int index = 1;\n int prev = head->val;\n struct ListNode *curr = head;\n struct ListNode *next = head->next;\n\n while (next) {\n if ((prev > curr->val && curr->val < next->val) || (prev < curr->val && curr->val > next->val)) {\n critical_indexes[critical_index_num++] = index;\n }\n\n prev = curr->val;\n curr = curr->next;\n next = next->next;\n index++;\n }\n\n // If there is no more than 1 critical points, it cannot get the distances\n if (critical_index_num <= 1) {\n free(critical_indexes);\n return result;\n }\n\n // Find min distance\n int min_dist = 1e6;\n for (int i = 1; i < critical_index_num; ++i) {\n min_dist = fmin(min_dist, critical_indexes[i] - critical_indexes[i - 1]);\n }\n\n result[0] = min_dist;\n result[1] = critical_indexes[critical_index_num - 1] - critical_indexes[0];\n\n // Free source\n free(critical_indexes);\n return result;\n}\n```\n```C++ []\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n if (head == nullptr)\n return {-1, -1};\n int prev = head->val;\n ListNode *first = head;\n ListNode *second = head->next;\n\n vector<int> critical_indexes;\n\n int index = 1;\n\n while (second) {\n if ((prev > first->val && first->val < second->val) || (prev < first->val && first->val > second->val)) {\n critical_indexes.push_back(index);\n }\n\n prev = first->val;\n first = first->next;\n second = second->next;\n index++;\n }\n\n if (critical_indexes.size() <= 1) {\n return {-1, -1};\n }\n\n // Find min distance\n int min_dist = INT_MAX;\n for (int i = 1; i < critical_indexes.size(); ++i) {\n min_dist = min(min_dist, critical_indexes[i] - critical_indexes[i - 1]);\n }\n\n return {min_dist, critical_indexes.back() - critical_indexes[0]};\n }\n};\n```
2
0
['Linked List', 'C', 'C++']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Efficiently Find Distances Between Critical Points in a Linked List ✅🧑‍💻
efficiently-find-distances-between-criti-pgnd
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
muhammadsahad
NORMAL
2024-07-05T06:15:12.449053+00:00
2024-07-05T06:15:12.449082+00:00
37
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O ( n )\n<!-- Add your time c**Bold**omplexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O ( n )\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @return {number[]}\n */\nvar nodesBetweenCriticalPoints = function (head) {\n\n let res = []\n let index = 0;\n let node = head\n let prev = 0;\n let arr = []\n\n while (node !== null && node.next !== null) {\n index++\n if (prev && (prev < node.val && node.next.val < node.val)\n || (prev > node.val && node.next.val > node.val)) {\n arr.push(index)\n }\n prev = node.val\n node = node.next\n }\n\n if (arr.length < 2) return [-1, -1]\n let min = Infinity ;\n let n = arr.length - 1\n let max = arr[n] - arr[0]\n let diff = 0\n\n for (let i = 1; i < arr.length; i++) {\n\n min = Math.min(min,arr[i] - arr[i-1])\n }\n return [min, max]\n};\n```
2
0
['JavaScript']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
🚀 Find Nodes Between Critical Points in Linked List! 🔗 Beats 57% ✨Memory Efficiency 82%
find-nodes-between-critical-points-in-li-xqul
\n\n# Intuition\nTo determine the distances between critical points in a linked list, we need to identify nodes that represent local maxima or minima. By traver
UDAY-SANKAR-MUKHERJEE
NORMAL
2024-07-05T05:46:04.987857+00:00
2024-07-05T05:46:04.987887+00:00
42
false
![image.png](https://assets.leetcode.com/users/images/75586082-165f-4b7d-869c-14bba3383591_1720158337.4186997.png)\n\n# Intuition\nTo determine the distances between critical points in a linked list, we need to identify nodes that represent local maxima or minima. By traversing the list and tracking these critical points, we can compute both the minimum and maximum distances between them.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Edge Case Handling: If the list has fewer than three nodes, return [-1, -1] since there can\'t be any critical points.\n2. Identify Critical Points:\n\u2022 Traverse the list while keeping track of the previous, current, and next nodes.\n\u2022 Identify a node as a critical point if it\'s either a local maximum or a local minimum.\n3. Calculate Distances:\n\u2022 If fewer than two critical points are found, return [-1,-1].\n\u2022 Otherwise, compute the minimum and maximum distances between the critical points.\n\n# Detailed Steps\n1. Initialize Pointers: Start with prev* as the head, curr\u2022 as the second node, and position\ncounter at I.\n2. Traverse List: Iterate through the list, checking if the current node is a critical point (either a local\nmaximum or minimum).\n3. Store Positions: Keep track of the positions of critical points.\n4. Calculate Minimum and Maximum Distances:\n- If fewer than two critical points exist, retum [-1,-1].\n- Compute the minimum distance between consecutive critical points.\n- Compute the maximum distance between the first and last critical points.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n), where n is the number of nodes in the linked list. Each node is visited exactly once.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1), as we use a fixed amount of extra space for pointers and the list to store critical points\' positions.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:\n if not head or not head.next or not head.next.next:\n return [-1, -1]\n\n critical_points = []\n prev = head\n curr = head.next\n position = 1\n\n while curr.next:\n if (curr.val > prev.val and curr.val > curr.next.val) or (curr.val < prev.val and curr.val < curr.next.val):\n critical_points.append(position)\n prev = curr\n curr = curr.next\n position += 1\n\n if len(critical_points) < 2:\n return [-1, -1]\n\n min_distance = float(\'inf\')\n max_distance = critical_points[-1] - critical_points[0]\n\n for i in range(1, len(critical_points)):\n min_distance = min(min_distance, critical_points[i] - critical_points[i - 1])\n\n return [min_distance, max_distance] \n```\nIf you found this helpful, please upvote! \uD83D\uDC4D\n![main-qimg-a645ae706f7acacc929d906ca22011cd-lq.jpg](https://assets.leetcode.com/users/images/f37233e0-b923-4108-bf4f-00562ff19bd4_1720158144.4913414.jpeg)\n
2
0
['Python3']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Simple Solution
simple-solution-by-csivaprakash-qxjk
Approch\n\nWe define previous node for compare the current node value to its previous node value and take the current node from next node to the head. \n\nThen
csivaprakash
NORMAL
2024-07-05T04:55:39.723617+00:00
2024-07-06T16:44:16.016640+00:00
65
false
# Approch\n\nWe define previous node for compare the current node value to its previous node value and take the current node from next node to the head. \n\nThen define startingPosition and previousPosition with value -1 and position (current position of the current node) with value 1.\n\nThen define int array of result = [-1, -1], where 0th index represents minimum distance and 1th index represents maximum distance.\n\nTraverse the current node untill the next node not null. In that if the current node value less/greater than both the previous node value and next node value it is a critcal Point.\n\nIf it is a critical point then we take position to the startingPosition if it is a first time and in rest of the iterations if it is a critical point take the difference with previousPosition (previous critical point) and compare to the 0th index of result (minimum distance) and change the 0th index value to minimum and take the difference with position and startingPosition and assign it to the 1th index of the result (maximum distance) and take the current position as a previousPosition.\n\nThen take the current node as previous node, move current node to next node and increase the position for next iteration\n\nFinally return the result.\n\nwww.instagram.com/sivaprakashktm\n\n\n\n\n\n# Code\n```\n\npublic class Solution {\n public int[] NodesBetweenCriticalPoints(ListNode head) {\n\n ListNode previous = head;\n ListNode current = head.next;\n\n int startingPosition = -1;\n int previousPosition = -1;\n int position = 1;\n\n int[] result = new int[] {-1, -1};\n\n while (current.next != null) {\n if ((current.val > previous.val && current.val > current.next.val) || (current.val < previous.val && current.val < current.next.val)) {\n if (startingPosition == -1)\n startingPosition = position;\n\n if (previousPosition > -1) {\n if (result[0] > position - previousPosition || result[0] == -1)\n result[0] = position - previousPosition;\n result[1] = position - startingPosition;\n }\n previousPosition = position;\n }\n \n previous = current;\n current = current.next;\n position++;\n }\n \n return result;\n }\n}\n```
2
0
['Linked List', 'C#']
1
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
🚀Fast and ✔️Easiest Solution in C++[129 ms Beats 97.43%]
fast-and-easiest-solution-in-c129-ms-bea-srsl
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
zishan_0point1
NORMAL
2024-07-05T04:23:58.346612+00:00
2024-07-05T04:23:58.346651+00:00
94
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);\n vector<int> idx;\n \n ListNode *temp = head;\n int i = 2;\n while(temp->next != NULL && temp->next->next != NULL){\n if(temp->next == NULL || temp->next->next == NULL) break;\n int l = temp->val;\n int m = temp->next->val;\n int r = temp->next->next->val;\n\n bool isMn = l < m && m > r;\n bool isMx = l > m && m < r;\n\n if(isMn || isMx) idx.push_back(i);\n i++;\n temp = temp->next;\n }\n vector<int> ans;\n if(idx.size() < 2){\n ans.push_back(-1);\n ans.push_back(-1);\n return ans;\n }\n int mn = INT_MAX;\n for(int i = 1; i < idx.size(); i++) mn = min(mn, idx[i] - idx[i-1]);\n ans.push_back(mn);\n ans.push_back(idx.back()-idx[0]);\n return ans;\n }\n};\n```
2
0
['Linked List', 'C++']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Best Approach💯
best-approach-by-adwxith-qax6
Please let me know if this solution works for you. If you find it helpful, an upvote would be greatly appreciated!\uD83E\uDEE1\n\n# Complexity\n- Time complexit
adwxith
NORMAL
2024-07-05T04:12:17.952638+00:00
2024-07-05T04:12:17.952666+00:00
126
false
# Please let me know if this solution works for you. If you find it helpful, an upvote would be greatly appreciated!\uD83E\uDEE1\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @return {number[]}\n */\nvar nodesBetweenCriticalPoints = function (head) {\n\n\n let firstPoint = -1, lastPoint = -1\n let index = 0, minD = Infinity, maxD = -Infinity\n let cur = head.next, prev = head, next = head?.next?.next\n\n while ( next) {\n if (isCriticalPoint(prev.val,cur.val,next.val)) {\n\n if (firstPoint == -1) {\n firstPoint = index\n } else {\n maxD = Math.max(maxD, (index - firstPoint))\n }\n if (lastPoint !== -1) {\n minD = Math.min(minD, (index - lastPoint))\n }\n lastPoint = index\n }\n index++\n prev = cur\n cur = next\n next = next.next\n\n }\n return firstPoint !== lastPoint ? [minD, maxD] : [-1, -1]\n};\n\nfunction isCriticalPoint(prev, cur, next){\n return (prev > cur && next > cur) || (prev < cur && next < cur)\n}\n```
2
0
['JavaScript']
2
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
|| Easy simple clean code ||C++ 98.75 % ||
easy-simple-clean-code-c-9875-by-srimukh-wfe0
Intuition\n Describe your first thoughts on how to solve this problem. \nFind all the positions of Critical points and the 2 values required are minimum distanc
srimukheshsuru
NORMAL
2024-07-05T04:11:55.513278+00:00
2024-07-05T04:11:55.513309+00:00
9
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFind all the positions of Critical points and the 2 values required are minimum distance between any 2 critical points , you can find this by traversing over the positions array once. the second value is directly ```v[v.size()-1] - v[0]```. if the size of v is less than 2 then answer is $$ (-1,-1) $$ and also if there are less than 4 nodes then also answer will be same as previous.\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$ \n\n\n![image.png](https://assets.leetcode.com/users/images/aee5c41d-f0da-473a-aade-aee80e9c716f_1720152078.716186.png)\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n if(head == nullptr || head->next == nullptr || head->next->next == nullptr) {\n return {-1, -1};\n }\n ListNode* curr = head->next;\n ListNode* prev = head;\n int i=1;\n vector<int>v;\n while(curr->next !=NULL){\n int temp = curr->val;\n int p = prev->val;\n int n = curr->next->val;\n if(temp > p && temp>n){\n v.push_back(i);\n }\n if(temp < p && temp<n){\n v.push_back(i);\n }\n\n i++;\n prev = prev->next;\n curr = curr->next;\n }\n if(v.size() <2){\n return {-1,-1};\n }\n vector<int>ans;\n int mini = INT_MAX;\n for(int i=1;i<v.size();i++){\n mini = min(mini,v[i]-v[i-1]);\n }\n ans.push_back(mini);\n ans.push_back(v[v.size()-1] - v[0]);\n return ans;\n }\n};\n```\n\n![image.png](https://assets.leetcode.com/users/images/94f8e07b-a28d-4401-9bc3-b9e02d9e5e8b_1720152586.3470328.png)\n\n\n\n\n
2
0
['Linked List', 'C++']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Python3 Solution
python3-solution-by-motaharozzaman1996-ppzl
\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\n
Motaharozzaman1996
NORMAL
2024-07-05T02:53:04.261741+00:00
2024-07-05T02:53:04.261766+00:00
146
false
\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:\n left=head\n mid=head.next\n right=mid.next\n idx=2\n idxs=[]\n while right:\n if (mid.val>left.val and mid.val>right.val) or (mid.val<left.val and mid.val<right.val):\n idxs.append(idx)\n left=mid\n mid=right\n right=right.next\n idx+=1\n if len(idxs)<2:\n return [-1,-1]\n min_dis=float(\'inf\')\n max_dis=idxs[-1]-idxs[0]\n for i in range(1,len(idxs)):\n min_dis=min(min_dis,idxs[i]-idxs[i-1])\n\n return [min_dis,max_dis] \n\n```
2
0
['Python', 'Python3']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
One Pass no extra space Easy Understanding ✅
one-pass-no-extra-space-easy-understandi-cwc3
Intuition\n\nKeep track of previous critical point and update minimum. \nfor maximum = last critical point - first critical point\n\n# Approach\n1. Identify Cri
yashwanthreddi
NORMAL
2024-07-05T01:07:05.633776+00:00
2024-07-14T05:46:01.592623+00:00
48
false
# Intuition\n\nKeep track of previous critical point and update minimum. \nfor maximum = last critical point - first critical point\n\n# Approach\n1. Identify Critical Points:\n\n- Traverse the linked list starting from the second node.\n- Check if a node is a local minimum or maximum by comparing its value with the previous and next node values.\n\n2. Track Critical Points:\n- Record the index of the first critical point found.\n- For subsequent critical points, update the minimum distance between consecutive critical points.\n- Update the index of the most recent critical point found.\n\n3. Calculate Distances:\n\n- After traversal, if fewer than two critical points are found, return {-1, -1}.\n- Otherwise, return the minimum distance between any two critical points and the distance between the first and last critical points.\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(1)\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n \n int i=2,prev_number =head->val,first_place=-1,prev_index=-1,mini=INT_MAX;\n \n ListNode* current = head->next;\n\n while(current && current->next)\n {\n\n if(current->val<prev_number && current->next && current->val<current->next->val || current->val>prev_number && current->next && current->val>current->next->val)\n {\n if(first_place == -1)\n first_place = i;\n \n if(prev_index!=-1)\n mini = min(mini,i-prev_index );\n\n prev_index = i;\n }\n\n i++;\n\n prev_number = current->val;\n current = current->next;\n }\n\n if(first_place == -1 || prev_index == -1 || mini == INT_MAX)\n {\n return {-1,-1};\n }\n\n return {mini,prev_index-first_place};\n }\n};\n```
2
0
['C++']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Easy C++ Solution || Using vectors
easy-c-solution-using-vectors-by-orewa_a-xhh4
Please upvote if you find this approach a little bit usefull.\n\n# Intuition\nThe question stated that we have to return the distance between the indices.\n\n#
Orewa_Abhi
NORMAL
2024-02-27T06:45:07.405456+00:00
2024-02-27T06:45:07.405491+00:00
256
false
# Please upvote if you find this approach a little bit usefull.\n\n# Intuition\nThe question stated that we have to return the distance between the **indices**.\n\n# Approach\n- Take a vector to store the indices of local minimas or maximas.\n- Declare an ind as 0 to count the indices of nodes.\n- Now use three pointers to traverse through the list ie prev,curr, next.\n- A value is a Local Minima or Local Maxima if and only if it has both prev and next nodes and either its neighbour should be strictly less than or greater than its value.\n- So traverse anc check accordingly, if it follows both of the above conditions, push the current ind value to the vector.\n- modify the prev, curr and next nodes and increment the ind by 1.\n- After getting the vector with the indices, if its size is less than 2 then we cannot calculate the distance so return **{-1,-1}** .\n- Calculate the max distance by subtracting the first and last element and min distance by substracting every immediate index value.\n- return **{mxD,mnD}**.\n\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n- Space complexity:\n$$O(n)$$\n# Code\n```\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n vector<int> inds;\n int ind = 0;\n ListNode* prev = NULL,*curr = head, *nxt = head->next;\n while(curr)\n {\n if(prev && nxt)\n {\n if((curr-> val > prev->val && curr->val > nxt->val) || curr-> val < prev->val && curr->val < nxt->val)\n {\n inds.push_back(ind);\n }\n }\n prev = curr;\n curr = curr->next;\n if(!curr->next) break;\n nxt = curr->next;\n ind++;\n }\n int mxD = INT_MIN, mnD = INT_MAX;\n if(inds.size() < 2) return {-1,-1};\n mxD = abs(inds[0] - inds[inds.size()-1]);\n for(int i = 0; i<inds.size()-1; i++)\n {\n mnD = min(mnD,inds[i+1]-inds[i]);\n }\n return {abs(mnD),abs(mxD)};\n }\n};\n```
2
0
['C++']
1
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
100% Efficient Solution in C++ with Linear Time Complexity O(n)...
100-efficient-solution-in-c-with-linear-2oeop
Intuition\n Describe your first thoughts on how to solve this problem. \nCheck Solution Comments written in Solution...\nDoes,...\n1). Atfirst, Read entire prob
ganpatinath07
NORMAL
2024-01-19T10:21:41.194385+00:00
2024-01-19T10:21:41.194420+00:00
87
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCheck Solution Comments written in Solution...\nDoes,...\n1). Atfirst, Read entire problem...\n2). Dry run atleast 3 testcases...\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUsing Basic concepts of Linked List...\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(Constant)\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n vector<int> ans = {-1, -1}; // for storing answer... ans[0] --> minDist, ans[1] --> maxDist...\n ListNode* prev = head;\n if(!prev) return ans; // Empty Linked List wala case...\n ListNode* curr = head->next;\n if(!curr) return ans; // Single element wala case...\n ListNode* nxt = head->next->next;\n if(!nxt) return ans; // Linked List m sirf 2 hi node h then, minDist and maxDist find krna possible nhi h a/c to problem...\n\n int firstCp = -1, lastCp = -1;\n int minDist = INT_MAX;\n int i = 1;\n\n while(nxt){\n bool isCp = ((curr->val > prev->val && curr->val > nxt->val) || (curr->val < prev->val && curr->val < nxt->val)) ? true : false;\n if(isCp && firstCp == -1){\n firstCp = lastCp = i;\n }\n else if(isCp){\n minDist = min(minDist, i - lastCp);\n lastCp = i;\n }\n ++i;\n prev = prev->next;\n curr = curr->next;\n nxt = nxt->next;\n }\n if(lastCp == firstCp)\n return ans; // coz, only 1 critical point available...\n else{\n ans[0] = minDist;\n ans[1] = lastCp - firstCp;\n }\n\n return ans;\n }\n};\n```
2
0
['Linked List', 'C++']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Easy Java Solution || T.C = O(n)
easy-java-solution-tc-on-by-ravikumar50-8kt0
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
ravikumar50
NORMAL
2023-09-17T08:30:45.422010+00:00
2023-09-17T08:30:45.422038+00:00
332
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public int[] nodesBetweenCriticalPoints(ListNode head) {\n int ans[] = new int[2];\n ans[0]= -1;\n ans[1] = -1;\n\n if(head==null || head.next==null || head.next.next==null) return ans;\n\n ArrayList<Integer> arr = new ArrayList<>();\n ListNode t = head.next;\n\n ListNode prev = head;\n int idx = 1;\n\n while(t.next!=null){\n if(t.val>prev.val && t.val>t.next.val) arr.add(idx);\n if(t.val<prev.val && t.val<t.next.val) arr.add(idx);\n\n idx++;\n prev = t;\n t=t.next;\n }\n\n if(arr.size()<2) return ans;\n\n ans[1] = arr.get(arr.size()-1) - arr.get(0);\n int min = Integer.MAX_VALUE;\n\n for(int i=1; i<arr.size(); i++){\n min = Math.min(arr.get(i)-arr.get(i-1),min);\n }\n ans[0] = min;\n return ans;\n\n }\n}\n```
2
0
['Java']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
easy c++ solution using vector || easy and optimal approach
easy-c-solution-using-vector-easy-and-op-vscn
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
Rhythm_1383
NORMAL
2023-08-20T14:32:12.703074+00:00
2023-08-20T14:32:12.703095+00:00
128
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n int count=2;\n vector<int>v;\n ListNode * temp=head->next;\n ListNode * prev=head;\n while(temp->next)\n {\n if(temp->val > prev->val && temp->val > temp->next->val)\n {\n v.push_back(count);\n }\n if(temp->val < prev->val && temp->val < temp->next->val)\n {\n v.push_back(count);\n }\n count++;\n prev=temp;\n temp=temp->next;\n }\n if(v.size()<2)\n {\n return {-1,-1};\n }\n sort(v.begin(), v.end()); // Sort the vector\n\n int maxDifference = v[v.size() - 1] - v[0];\n int minDifference = INT_MAX;\n\n for (int i = 1; i < v.size(); ++i) {\n int diff = v[i] - v[i - 1];\n minDifference = min(minDifference, diff);\n }\n return {minDifference,maxDifference};\n }\n};\n```
2
0
['C++']
1
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Golang Time O(n), Space O(1). Runtime Beats 100% & Memory Beats 100%
golang-time-on-space-o1-runtime-beats-10-41ey
Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(1)\n Add your space complexity here, e.g. O(n) \n\n# Co
tenseiganrinnesharingan
NORMAL
2023-03-31T19:14:53.721821+00:00
2023-04-01T07:40:18.724458+00:00
77
false
# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * type ListNode struct {\n * Val int\n * Next *ListNode\n * }\n */\nfunc nodesBetweenCriticalPoints(head *ListNode) []int {\n if head.Next.Next == nil {\n return []int{-1, -1}\n }\n\n min, max := -1, -1\n\n prev := head\n head = head.Next\n prevIndex, firstIndex := -1, -1\n curIndex := 1\n \n for head.Next != nil {\n if (head.Val < prev.Val && head.Val < head.Next.Val) || (head.Val > prev.Val && head.Val > head.Next.Val) {\n if prevIndex == -1 {\n prevIndex = curIndex\n firstIndex = curIndex\n } else {\n max = curIndex - firstIndex\n if curIndex - prevIndex < min || min == -1 {\n min = curIndex - prevIndex\n }\n prevIndex = curIndex\n }\n }\n prev = head\n head = head.Next\n curIndex++\n }\n\n return []int{min, max}\n}\n```
2
0
['Go']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
c++ easy samaj me aaega bro
c-easy-samaj-me-aaega-bro-by-underdogsou-l1tw
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
underdogsourav
NORMAL
2023-03-26T15:46:04.984064+00:00
2023-03-26T15:46:04.984101+00:00
391
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n vector<int> ans(2,-1);\n if(head==NULL || head->next==NULL || head->next->next==NULL || head->next->next->next==NULL){\n return ans;\n }\n ListNode* prev=head;\n ListNode* nex=head->next->next;\n ListNode* cur=head->next;\n int index=1;\n vector<int> points;\n while(nex){\n if(cur->val<prev->val && cur->val<nex->val){\n points.push_back(index);\n }\n if(cur->val>prev->val && cur->val>nex->val){\n points.push_back(index);\n }\n index++;\n prev=prev->next;\n cur=cur->next;\n nex=nex->next;\n\n }\n int minn= INT_MAX;\n int maxx=INT_MIN;\n if(points.size()<2){\n return ans;\n }\n sort(points.begin(),points.end());\n for(int i=0;i<points.size()-1;i++){\n minn=min(minn,abs(points[i]-points[i+1]));\n }\n maxx=abs(points[0]-points[points.size()-1]);\n ans[0]=minn;\n ans[1]=maxx;\n return ans;\n }\n};\n```
2
0
['C++']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
c++ || easy to understand
c-easy-to-understand-by-pawanchaudhary02-y59h
\'\'\' \nvector nodesBetweenCriticalPoints(ListNode head) {\n\n int mini=INT_MAX;\n ListNode cur=head->next,*pre=head;\n if(head==NULL |
pawanchaudhary026
NORMAL
2022-06-30T19:30:47.581520+00:00
2022-06-30T19:30:47.581566+00:00
196
false
\'\'\' \nvector<int> nodesBetweenCriticalPoints(ListNode* head) {\n\n int mini=INT_MAX;\n ListNode *cur=head->next,*pre=head;\n if(head==NULL || cur->next==NULL)\n return {-1,-1};\n int ind=1;\n int ind1=0,ind2=0;\n // count is using for maxDistance by adding the distance btw two critical points\n int count=0;\n while(cur->next)\n {\n // for local minima\n if(pre->val > cur->val && cur->val< cur->next->val)\n {\n if(ind1==0)\n ind1=ind;\n else\n ind2=ind;\n \n \n }\n // for local maxima\n else if(pre->val < cur->val && cur->val > cur->next->val)\n {\n if(ind1==0)\n ind1=ind;\n else\n ind2=ind;\n \n } \n if(ind1!=0 && ind2!=0)\n {\n mini=min(mini,ind2-ind1);\n count+=ind2-ind1;\n ind1=ind2;\n ind2=0;\n } \n pre=cur;\n cur=cur->next;\n ind++;\n \n }\n // if we don\'t have any critcal point\n if(mini==INT_MAX || count==0)\n return {-1,-1};\n return {mini,count};\n }\n\'\'\'
2
0
[]
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Easy To Understand Python Solution
easy-to-understand-python-solution-by-da-1h7n
Hope this helps!\n\n~First of all, we first create two pointer, curr and prev to track previous and current node. We can keep track the node after curr using cu
danielkua
NORMAL
2022-03-14T00:30:55.500451+00:00
2022-03-14T00:36:22.624364+00:00
82
false
Hope this helps!\n\n~First of all, we first create two pointer, `curr` and `prev` to track previous and current node. We can keep track the node after curr using `curr.next`. So we only require 2 pointer here.\n\n~Then, we keep track the index of the curr node using `count` at the beginning and set it at 0. Whenever `curr = curr.next`, `count` increases by one. Note that `(count + 1)` is used in the code so that the index starts at 1 instead of 0-indexing. \n\n~ We create one tmp array and one res array that we return at the end. \n\nWe append the count to tmp array when \n1) `curValue` > `cur.next.val` and `curValue > prevValue` OR \n2) `curValue` <` prevValue` and `curValue` < `cur.next.val`\n\n\n~Since the tmp array is sorted when we keep track of the index of the node, the maximum distance will be tmp[-1] - tmp[0] at the end or we can also keep track using `maxi = max(maxi, tmp[-1] - tmp[0])`.\n\n~Since we do not know the minimum distance between two critical points, we will keep track of minimum distance when `len(tmp) > 2`. I used `mini = min(mini, tmp[-1] - tmp[-2])` here.\n\n\nAt the end, we append (min distance, max distance) to res. Min distance wound be `mini` and max distance would be tmp[-1] - tmp[0]. (Ending index) - (starting index) will result in the maximum distance since the arr is sorted as we loop from left to right.\n \nWe check the len(tmp) at the end. If there is less than 2 distinct nodes in tmp, we return\n[-1,-1]. Else we return [mini, maxi] distances of the 2 distinct nodes.\n\n\n```\nclass Solution:\n def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:\n cur = head\n prev = cur\n tmp = []\n res = []\n count = 0\n mini = float(\'inf\')\n\n while cur.next:\n curValue = cur.val\n if count >= 1:\n prevValue = prev.val\n\n if curValue > cur.next.val and curValue > prevValue:\n tmp.append(count + 1)\n elif curValue < prevValue and curValue < cur.next.val:\n tmp.append(count + 1)\n\n prev = prev.next\n if len(tmp) > 1:\n mini = min(mini, tmp[-1] - tmp[-2])\n\t\t\t\t\t#alternative\n\t\t\t\t\t#maxi = max(maxi, tmp[-1] - tmp[0])\n\n cur = cur.next\n count += 1\n\n if len(tmp) < 2:\n return [-1, -1]\n else:\n return [mini, (tmp[-1] - tmp[0])] \n\t\t\t\n\t\t\t#alternative\n\t\t\t#return [mini, maxi]\n\n```
2
0
['Python', 'Python3']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
C++ simple and clean solution, Time O(N).
c-simple-and-clean-solution-time-on-by-p-t5kr
// By using extra space ie. a vector \n// Time O(N) Space O(N)\n\nclass Solution {\npublic:\n vector nodesBetweenCriticalPoints(ListNode head) {\n Lis
Puneet_Singh07
NORMAL
2022-02-07T09:31:31.688947+00:00
2022-02-07T09:33:54.183377+00:00
134
false
// By using extra space ie. a vector \n// Time O(N) Space O(N)\n\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n ListNode* prev= head;\n ListNode* curr=head->next;\n ListNode* after=curr->next;\n if(prev==NULL || curr==NULL || after==NULL)\n return {-1,-1};\n int i=2;\n vector<int>v;\n while(curr->next){\n \n if(curr->val>prev->val && curr->val >after->val)\n v.push_back(i);\n \n else if(curr->val<prev->val && curr->val < after->val)\n v.push_back(i);\n \n i++;\n prev=curr;\n curr=after;\n after=after->next;\n }\n if(v.size()==0 || v.size()==1)\n return{-1,-1};\n int sum=INT_MAX;\n for(int i=1;i<v.size();i++){\n int min1=v[i]-v[i-1];\n if(min1<sum)\n sum=min1;\n }\n int p=v[v.size()-1]-v[0];\n return {sum,p};\n \n }\n};\n\n\n// Without using extra space\n//Time O(N) and Space O(1)\n\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n ListNode* prev= head;\n ListNode* curr=head->next;\n ListNode* after=curr->next;\n \n if(prev==NULL || curr==NULL || after==NULL)\n return {-1,-1};\n int i=2,j=0,k=0,h=0;\n bool flag=false;\n int ans=INT_MAX;\n while(curr->next)\n {\n if((curr->val>prev->val && curr->val >after->val) || (curr->val<prev->val && curr->val < after->val))\n {\n // j is used for storing the first index at which we get maximum or minimum. \n if(j==0)\n j=i;\n else\n {\n // k is used for storing next maximum or minimum index, so as to calcumte min difference b/w them. \n flag=true;\n k=i;\n }\n if(flag==true)\n ans=min(ans,k-h);\n \n h=i;\n }\n i++;\n prev=curr;\n curr=after;\n after=after->next;\n }\n if((ans==INT_MAX || k==0) || (ans==INT_MAX && k==0))\n return {-1,-1};\n return {ans,k-j};\n \n }\n};
2
0
['Linked List', 'C']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
c++ easy soln
c-easy-soln-by-sahildalal23-6n7v
hint-store the indicies of critical points in array\n```\nclass Solution {\npublic:\n vector nodesBetweenCriticalPoints(ListNode head) {\n ListNode te
sahildalal23
NORMAL
2021-12-02T15:04:33.936995+00:00
2021-12-02T15:04:33.937025+00:00
128
false
hint-store the indicies of critical points in array\n```\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n ListNode* temp=head;\n ListNode* temp2=head->next;\n vector<int> v;\n int i=1;\n while(temp2->next!=NULL)\n {\n if(temp2->val>temp->val && temp2->val>temp2->next->val || temp2->val<temp->val && temp2->val<temp2->next->val )\n {\n v.push_back(i);\n }\n i++;\n temp2=temp2->next;\n temp=temp->next;\n }\n if(v.size()<2)\n {\n return {-1,-1};\n }\n int mini=INT_MAX;\n for(int i=1;i<v.size();i++)\n {\n mini=min(mini,v[i]-v[i-1]);\n }\n return {mini,v[v.size()-1]-v[0]};\n \n }\n};
2
0
[]
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
(C++) 2058. Find the Minimum and Maximum Number of Nodes Between Critical Points
c-2058-find-the-minimum-and-maximum-numb-jgwh
\n\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n int dmin = INT_MAX, last = 0, first = 0, prev = head->val,
qeetcode
NORMAL
2021-11-01T21:20:03.630786+00:00
2021-11-01T21:20:03.630817+00:00
146
false
\n```\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) {\n int dmin = INT_MAX, last = 0, first = 0, prev = head->val, i = 1; \n for (ListNode* node = head->next; node && node->next; prev = node->val, node = node->next, ++i) \n if ((prev < node->val && node->val > node->next->val) || (prev > node->val && node->val < node->next->val)) {\n if (last) dmin = min(dmin, i - last); \n if (!first) first = i; \n last = i; \n }\n if (dmin < INT_MAX) return {dmin, last - first}; \n return {-1, -1}; \n }\n};\n```
2
0
['C']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Python3 - O(n) Time | O(1) Space | Faster than 100%
python3-on-time-o1-space-faster-than-100-b402
\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\ncl
yukkk
NORMAL
2021-10-31T19:13:56.840236+00:00
2021-10-31T19:22:15.939935+00:00
209
false
```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:\n prev = head.val\n head = head.next\n if not head.next: return [-1, -1]\n \n first, last, currmin, curr = None, None, float("inf"), 1\n ahead = head.next\n while ahead:\n if prev > head.val < ahead.val or prev < head.val > ahead.val:\n if first is None: first = last = curr\n else:\n currmin = min(currmin, curr - last)\n last = curr\n prev, curr = head.val, curr + 1\n head, ahead = head.next, ahead.next\n \n return [currmin, last - first] if currmin != float("inf") else [-1, -1]\n```\nRuntime: 924 ms\nMemory Usage: 55.1 MB
2
0
[]
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Bruh this is the easiest solution you can find
bruh-this-is-the-easiest-solution-you-ca-7sd1
maximum distance - first and last critical points\nminimum distance - between the 2 neighboring critical points\n\n/**\n * Definition for singly-linked list.\n
aparna_g
NORMAL
2021-10-31T17:21:12.052666+00:00
2021-10-31T17:21:12.052708+00:00
136
false
**maximum distance - first and last critical points\nminimum distance - between the 2 neighboring critical points**\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n vector<int> nodesBetweenCriticalPoints(ListNode* head) { \n vector<int> criticalPoints; \n int i=1; \n ListNode* curr = head->next; \n int prev = head->val ; \n while(curr->next) {\n if(curr->val > prev && curr->val> curr->next->val) \n criticalPoints.push_back(i); \n else if(curr->val < prev && curr->val < curr->next->val)\n criticalPoints.push_back(i); \n prev = curr->val; \n curr = curr->next; \n i++;\n } \n if(criticalPoints.size()<2) {\n return {-1,-1}; \n }\n vector<int> result; \n int minDist = INT_MAX;\n for(int i=1;i<criticalPoints.size();i++) {\n minDist = min(minDist , criticalPoints[i]-criticalPoints[i-1]); \n }\n result.push_back(minDist); \n result.push_back(criticalPoints[criticalPoints.size()-1] - criticalPoints[0]);\n return result; \n }\n};\n```
2
1
['C', 'C++']
1
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Python Easy Solution : Weekly Contest 265 : Que 2058
python-easy-solution-weekly-contest-265-le6pk
\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\ncl
deleted_user
NORMAL
2021-10-31T04:33:11.682041+00:00
2021-10-31T04:33:11.682076+00:00
85
false
```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]:\n s1 = []\n s2 = []\n curr = head.next\n prev = head\n i = 2\n while curr.next:\n if prev.val < curr.val > curr.next.val:\n s1.append([curr.val,i])\n elif prev.val > curr.val < curr.next.val:\n s2.append([curr.val, i])\n i += 1\n prev = curr\n curr = curr.next\n\n res = []\n for each in s1:\n res.append(each[1])\n for each in s2:\n res.append(each[1])\n if len(res) < 2:\n return [-1,-1]\n res.sort()\n\n mx = max(res) - min(res)\n diff = math.inf\n for i in range(len(res)-1):\n if res[i + 1] - res[i] < diff:\n diff = res[i + 1] - res[i]\n return [diff,mx]\n```
2
1
['Python3']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
✅Beats 100% Easy O(N) C++ solution 🔥
beats-100-easy-on-c-solution-by-bytemaes-dfsd
Complexity Time complexity: O(N) Code
ByteMaestro56
NORMAL
2025-04-04T18:31:26.113141+00:00
2025-04-04T18:31:26.113141+00:00
9
false
# Complexity - Time complexity: O(N) # Code ```cpp [] /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: vector<int> nodesBetweenCriticalPoints(ListNode* head) { ListNode*temp=head->next; int prev=head->val,curr=temp->val,nex,crit=-1000000,start=0,count=1,mini=INT_MAX,pointcount=0; while(temp&&temp->next){ temp=temp->next; nex=temp->val; if(prev>curr&&nex>curr||prev<curr&&nex<curr){ if(start==0)start=count; mini=min(mini,count-crit); crit=count; pointcount++; } prev=curr; curr=nex; count++; } if(pointcount<2)return{-1,-1}; return {mini,crit-start}; } }; ```
1
0
['C++']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
Find Critical Points, the Jedi Way
find-critical-points-the-jedi-way-by-x7f-2yq0
IntuitionHmm... Identify peaks and valleys in the linked list we must. Like sensing the highs and lows of the Force, critical points we shall find. Between them
x7Fg9_K2pLm4nQwR8sT3vYz5bDcE6h
NORMAL
2025-03-27T16:49:54.994352+00:00
2025-03-27T16:49:54.994352+00:00
10
false
# Intuition Hmm... Identify peaks and valleys in the linked list we must. Like sensing the highs and lows of the Force, critical points we shall find. Between them, the minimum and maximum distances calculate we will. # Approach 1. Traverse the list: Examine each node with its neighbors 2. Identify critical points: Mark local maxima and minima positions 3. Calculate distances: - Minimum distance between adjacent critical points - Maximum distance between first and last critical points 4. Handle edge cases: Return [-1, -1] if fewer than 2 critical points exist # Complexity - Time complexity: $$O(n)$$ - Space complexity: $$O(1)$$ # Code ```cpp [] /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: vector<int> nodesBetweenCriticalPoints(ListNode* head) { vector<int>ans; int x=0; while (head->next->next!=NULL){ if ((head->val<head->next->val && head->next->val>head->next->next->val) || (head->val>head->next->val && head->next->val<head->next->next->val)){ ans.push_back(x+1); } head=head->next; x++; } if (ans.size()<2){return {-1,-1};} int mi=INT_MAX,ma=INT_MIN; for (int i=0;i<ans.size()-1;i++){mi=min(mi,abs(ans[i+1]-ans[i]));} ma=ans.back()-ans[0]; return {mi,ma}; } }; ```
1
0
['C++']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
100% beats|| easy and simple approach||
100-beats-easy-and-simple-approach-by-ro-4qzo
IntuitionApproachComplexity Time complexity: Space complexity: Code
Rohan07_6473
NORMAL
2025-03-14T12:02:10.283701+00:00
2025-03-14T12:02:10.283701+00:00
15
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: vector<int> nodesBetweenCriticalPoints(ListNode* head) { vector<int> ans(2, -1); if (!head || !head->next || !head->next->next) return ans; ListNode* prev = head; head = head->next; // Move to the second node vector<int> criticalPoints; int index = 1; // Start indexing from 1 while (head->next) { // Ensure `head->next` exists if ((prev->val < head->val && head->val > head->next->val) || (prev->val > head->val && head->val < head->next->val)) { criticalPoints.push_back(index); } prev = head; // Move `prev` first head = head->next; // Move to the next node index++; } if (criticalPoints.size() < 2) return ans; // At least two critical points required int minDist = INT_MAX; for (int i = 1; i < criticalPoints.size(); i++) { minDist = min(minDist, criticalPoints[i] - criticalPoints[i - 1]); } ans[0] = minDist; ans[1] = criticalPoints.back() - criticalPoints.front(); return ans; } }; ```
1
0
['C++']
0
find-the-minimum-and-maximum-number-of-nodes-between-critical-points
C#
c-by-adchoudhary-vqex
Code
adchoudhary
NORMAL
2025-03-05T03:51:21.415805+00:00
2025-03-05T03:51:21.415805+00:00
6
false
# Code ```csharp [] /** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int val=0, ListNode next=null) { * this.val = val; * this.next = next; * } * } */ public class Solution { public int[] NodesBetweenCriticalPoints(ListNode head) { int[] result = { -1, -1 }; // Initialize minimum distance to the maximum possible value int minDistance = int.MaxValue; // Pointers to track the previous node, current node, and indices ListNode previousNode = head; ListNode currentNode = head.next; int currentIndex = 1; int previousCriticalIndex = 0; int firstCriticalIndex = 0; while (currentNode.next != null) { // Check if the current node is a local maxima or minima if ((currentNode.val < previousNode.val && currentNode.val < currentNode.next.val) || (currentNode.val > previousNode.val && currentNode.val > currentNode.next.val)) { // If this is the first critical point found if (previousCriticalIndex == 0) { previousCriticalIndex = currentIndex; firstCriticalIndex = currentIndex; } else { // Calculate the minimum distance between critical points minDistance = Math.Min(minDistance, currentIndex - previousCriticalIndex); previousCriticalIndex = currentIndex; } } // Move to the next node and update indices currentIndex++; previousNode = currentNode; currentNode = currentNode.next; } // If at least two critical points were found if (minDistance != int.MaxValue) { int maxDistance = previousCriticalIndex - firstCriticalIndex; result = new int[] { minDistance, maxDistance }; } return result; } } ```
1
0
['C#']
0