How to Solve LeetCode Problem #941: Valid Mountain Array

🚀 Day 45 of #100DaysOfCode – LeetCode Problem #941: Valid Mountain Array 💬 Problem Summary: Given an array of integers, determine whether it forms a valid mountain shape. A valid mountain must: Strictly increase to a single peak Then strictly decrease Have at least 3 elements No plateaus allowed (no equal adjacent numbers) 🧩 Examples: Input: [0,3,2,1] Output: true Input: [3,5,5] Output: false (plateau — invalid) 🧠 Logic: A mountain has two phases: 1️⃣ Climbing up: Move from the left while each next number is greater. 2️⃣ Climbing down: Move from the right while each next number is smaller. If both pointers meet at the same peak, and the peak isn't at the edge → it's a valid mountain. 💻 Java Solution: class Solution { public boolean validMountainArray(int[] A) { if (A.length < 3) return false; int n = A.length, L = 0, R = n - 1; // Walk up while (L < n - 1 && A[L] < A[L + 1]) { L++; } // Walk down while (R > 0 && A[R] < A[R - 1]) { R--; } // Check if L and R meet at a valid peak return L == R && L != 0 && R != n - 1; } } ⚙️ Complexity: Time: O(n) Space: O(1) ✅ Result: Accepted (Runtime: 0 ms) 💬 Takeaway: Two-pointer strategies are incredibly powerful for problems with clear directional patterns. This one becomes simple once you think of the array as a climb + descent.

To view or add a comment, sign in

Explore content categories