Finding Min & Max in Array and First & Last Occurrence of Element

Day 67/100 — #100DaysOfCode Today , Worked on two problems: 𝐅𝐢𝐧𝐝𝐢𝐧𝐠 𝐦𝐢𝐧𝐢𝐦𝐮𝐦 𝐚𝐧𝐝 𝐦𝐚𝐱𝐢𝐦𝐮𝐦 𝐢𝐧 𝐚𝐧 𝐚𝐫𝐫𝐚𝐲 𝐅𝐢𝐧𝐝𝐢𝐧𝐠 𝐟𝐢𝐫𝐬𝐭 𝐚𝐧𝐝 𝐥𝐚𝐬𝐭 𝐨𝐜𝐜𝐮𝐫𝐫𝐞𝐧𝐜𝐞 𝐨𝐟 𝐚 𝐭𝐚𝐫𝐠𝐞𝐭 𝐢𝐧 𝐚 𝐬𝐨𝐫𝐭𝐞𝐝 𝐚𝐫𝐫𝐚𝐲 𝟏. 𝐌𝐢𝐧 & 𝐌𝐚𝐱 𝐢𝐧 𝐀𝐫𝐫𝐚𝐲(Brute Force clarity) At first glance, it’s simple — but the real learning was the mental model. Instead of guessing whether a number is min or max, I learned: Always keep a reference (minVal, maxVal) Compare every element with that reference Update accordingly Core idea: Don’t judge a number in isolation, compare it with what you already know. Time complexity: O(n) because every element must be seen. 𝟐. 𝐅𝐢𝐫𝐬𝐭 & 𝐋𝐚𝐬𝐭 𝐏𝐨𝐬𝐢𝐭𝐢𝐨𝐧 𝐨𝐟 𝐄𝐥𝐞𝐦𝐞𝐧𝐭 (Binary Search shift) My initial instinct was: Traverse array Maybe sort But that completely breaks the constraint. Since the array is already sorted and O(log n) is required, the correct approach is: Use Binary Search Not once, but twice: First occurrence → move left Last occurrence → move right Core idea: When sorted + fast search is required → think Binary Search, not loops. I’m starting to see a pattern: Problems are not about code first They are about choosing the right approach Wrong thinking → correct code won’t save you Right thinking → code becomes easy On to Day 68

  • graphical user interface, application

To view or add a comment, sign in

Explore content categories