
Hi! My name is Nhut Nguyen. I am a software engineer and a writer in Copenhagen, Denmark.
Learn more about me at nhutnguyen.com
Search for a command to run...

Hi! My name is Nhut Nguyen. I am a software engineer and a writer in Copenhagen, Denmark.
Learn more about me at nhutnguyen.com
No comments yet. Be the first to comment.
A simple example of using C++ switch

Two dynamic programming techniques to solve Leetcode 120. Triangle. One has space complexity O(n^2). The other is O(n).

An example of using a sliding window approach and an unordered map to track character positions

A simple C++ solution to Leetcode 1695. Maximum Erasure Value using a sliding window approach and prefix sums.

Strategies to avoid them will help you excel in your following technical interview

Given an array of integers arr, return true if and only if it is a valid mountain array.
Recall that arr is a mountain array if and only if:
arr.length >= 3
There exists some i with 0 < i < arr.length - 1 such that:
arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
arr[i] > arr[i + 1] > ... > arr[arr.length - 1]

Input: arr = [2,1]
Output: false
Input: arr = [3,5,5]
Output: false
Input: arr = [0,3,2,1]
Output: true
1 <= arr.length <= 10^4.
0 <= arr[i] <= 10^4.
Following the conditions, we have the following implementation.
#include <vector>
#include <iostream>
using namespace std;
bool validMountainArray(vector<int>& arr) {
if (arr.size() < 3) {
return false;
}
const int N = arr.size() - 1;
int i = 0;
while (i < N && arr[i] < arr[i + 1]) {
i++;
}
if (i == 0 || i == N) {
return false;
}
while (i < N && arr[i] > arr[i + 1]) {
i++;
}
return i == N;
}
int main() {
vector<int> arr{2,1};
cout << validMountainArray(arr) << endl;
arr = {3,5,5};
cout << validMountainArray(arr) << endl;
arr = {0,3,2,1};
cout << validMountainArray(arr) << endl;
arr = {9,8,7,6,5,4,3,2,1,0};
cout << validMountainArray(arr) << endl;
}
Output:
0
0
1
0
Runtime: O(N), where N = arr.length.
Extra space: O(1).
Thanks for reading. Feel free to share your thought about my content and check out my FREE book “10 Classic Coding Challenges”.