Загрузка страницы

Total Occurrences Of K In A Sorted Array (Facebook Software Engineering Interview Question)

Free 5-Day Mini-Course: https://backtobackswe.com
Try Our Full Platform: https://backtobackswe.com/pricing
📹 Intuitive Video Explanations
🏃 Run Code As You Learn
💾 Save Progress
❓New Unseen Questions
🔎 Get All Solutions
Subscribe To Live Tech Offers: https://offerfeed.io
Join Our Coaching Service: https://backtobackswe.com/coaching

Question: Given a sorted array, find the total count of occurrences of a given value K as efficiently as possible. (Hint: The best answer runs in O(log(n)) time)

This was a question that I got in my 1st round Facebook interview. Error: At 3:27 the "Answer" should have said 1. Sorry.

Approach 1:
Linear scan and count
Time: O(N)
Space: O(1)

Remember: whenever an array is sorted it automatically unlocks binary search which is very fast. Binary search should be first on your mind and you should tell your interviewer so immediately.

Binary search operates off what is called an invariant. Our invariant is that no matter how often we split the search space, the space will stay sorted and hence again binary search can be used on it (doesn't have to be perfectly sorted though as we will see in other problems)

Approach 2:
Binary search for the first element and then linear scan to count the elements from that first element to its last occurrence.

Average Case
Time: O(log(n))
Space: O(1)

Worst Case
Time: O(N)
Space: O(1) [O(log(n) if the binary search is recursive]

This is the approach that I was stuck on, but my interviewer then said, "Can we keep it log(n) in every case?"

Then I knew that we would only be dealing with binary searches, any linear scans would be unnecessary

I knew I needed to get the count somehow so it occurred to me...if it is sorted, the lastOccurrence will give us the count if we just subtract the first occurrence from it and add 1. That is the total elements between the first and last occurrence and they all must be that number itself since the array is sorted

Approach 3:
Binary search for the first occurrence. If not found then return 0 occurrences total. If found, binary search for the 2nd element.

The answer is: lastOccurrence - firstOccurrence + 1

Time: O(log(n)) + O(log(n)) = O(log(n))
Space: O(1) [O(log(n)) if the binary search is recursive]

Takeaways:

-) If an array is sorted, immediately think binary search even if the problem is not a search problem (in this case it is)

-) Be vocal, your interviewer will guide you. Say approaches that may even be suboptimal, they may be close to the optimal result

+++++++++++++++++++++++++++++++++++++++++++++++++++

HackerRank: https://www.youtube.com/channel/UCOf7UPMHBjAavgD0Qw5q5ww

Tuschar Roy: https://www.youtube.com/user/tusharroy2525

GeeksForGeeks: https://www.youtube.com/channel/UC0RhatS1pyxInC00YKjjBqQ

Jarvis Johnson: https://www.youtube.com/user/VSympathyV

Success In Tech: https://www.youtube.com/channel/UC-vYrOAmtrx9sBzJAf3x_xw

++++++++++++++++++++++++++++++++++++++++++++++++++

Видео Total Occurrences Of K In A Sorted Array (Facebook Software Engineering Interview Question) канала Back To Back SWE
Показать
Комментарии отсутствуют
Введите заголовок:

Введите адрес ссылки:

Введите адрес видео с YouTube:

Зарегистрируйтесь или войдите с
Информация о видео
12 декабря 2018 г. 21:14:25
00:14:04
Другие видео канала
How To Permute A String - Generate All Permutations Of A StringHow To Permute A String - Generate All Permutations Of A StringFacebook Coding Interview Question - First and Last Position of X in Sorted ArrayFacebook Coding Interview Question - First and Last Position of X in Sorted ArrayFind The Second Largest Item - Heap & Tracking Approach (Beginner Big N Interview Question)Find The Second Largest Item - Heap & Tracking Approach (Beginner Big N Interview Question)LeetCode Find First and Last Position of Element in Sorted Array Solution Explained - JavaLeetCode Find First and Last Position of Element in Sorted Array Solution Explained - JavaDepth First & Breadth First Graph Search - DFS & BFS Graph Searching AlgorithmsDepth First & Breadth First Graph Search - DFS & BFS Graph Searching AlgorithmsFacebook Coding Interview Question - sortedSquaredArrayFacebook Coding Interview Question - sortedSquaredArrayAll Nodes Distance K In A Binary Tree - Performing Bidirectional Search On A Tree Using A HashtableAll Nodes Distance K In A Binary Tree - Performing Bidirectional Search On A Tree Using A HashtableWas 2020 A Simulation? (Science & Math of the Simulation Theory)Was 2020 A Simulation? (Science & Math of the Simulation Theory)Implement A Binary Heap - An Efficient Implementation of The Priority Queue ADT (Abstract Data Type)Implement A Binary Heap - An Efficient Implementation of The Priority Queue ADT (Abstract Data Type)How To Get A Job At Google | The Ultimate Guide To Algorithmic/Coding InterviewsHow To Get A Job At Google | The Ultimate Guide To Algorithmic/Coding InterviewsEdit Distance Between 2 Strings - The Levenshtein Distance ("Edit Distance" on LeetCode)Edit Distance Between 2 Strings - The Levenshtein Distance ("Edit Distance" on LeetCode)Math Has a Fatal FlawMath Has a Fatal FlawClone A Linked List (With Random Pointers) - Linear Space Solution & Tricky Constant Space SolutionClone A Linked List (With Random Pointers) - Linear Space Solution & Tricky Constant Space Solution5 Things I Wish I Knew Before Becoming a Software Engineer5 Things I Wish I Knew Before Becoming a Software EngineerThe Change Making Problem - Fewest Coins To Make Change Dynamic ProgrammingThe Change Making Problem - Fewest Coins To Make Change Dynamic ProgrammingAdd Two Numbers Without The "+" Sign (Bit Shifting Basics)Add Two Numbers Without The "+" Sign (Bit Shifting Basics)Interval Scheduling Maximization (Proof w/ Exchange Argument)Interval Scheduling Maximization (Proof w/ Exchange Argument)Binary Tree Bootcamp: Full, Complete, & Perfect Trees. Preorder, Inorder, & Postorder Traversal.Binary Tree Bootcamp: Full, Complete, & Perfect Trees. Preorder, Inorder, & Postorder Traversal.Search A Maze For Any Path - Depth First Search Fundamentals (Similar To "The Maze" on Leetcode)Search A Maze For Any Path - Depth First Search Fundamentals (Similar To "The Maze" on Leetcode)The Ultimate Big O Notation Tutorial (Time & Space Complexity For Algorithms)The Ultimate Big O Notation Tutorial (Time & Space Complexity For Algorithms)
Яндекс.Метрика