SP Data Structures and Algorithms 2 — Questions and Answers
Question 1: Which Salesforce collection type maintains insertion order and allows duplicate values?
- Set
- Map
- List (Correct answer)
- Queue
Correct answer: List
List in Apex maintains insertion order and permits duplicate elements, unlike Set which is unordered and unique.
Question 2: What is the time complexity of searching for an element in an unsorted Apex List?
- O(1)
- O(log n)
- O(n) (Correct answer)
- O(n²)
Correct answer: O(n)
Searching an unsorted list requires iterating through elements one by one, resulting in O(n) linear time.
Question 3: In Salesforce, which data structure is most appropriate for tracking unique Account IDs collected during a batch process?
- List<Id>
- Set<Id> (Correct answer)
- Map<Id,Id>
- Queue<Id>
Correct answer: Set<Id>
Set<Id> automatically enforces uniqueness, preventing duplicate IDs from being stored.
Question 4: A developer needs to count how many times each Status value appears across a list of Cases. Which approach is most efficient?
- Nested for loops comparing each Case
- A Map<String,Integer> incremented per Status (Correct answer)
- A Set<String> of Status values
- A sorted List<String> with binary search
Correct answer: A Map<String,Integer> incremented per Status
A Map keyed by Status with an Integer count value allows O(1) lookup and increment per record.
Question 5: Which sorting algorithm is generally most efficient for large, nearly-sorted datasets?
- Bubble Sort
- Selection Sort
- Insertion Sort (Correct answer)
- Quick Sort
Correct answer: Insertion Sort
Insertion Sort performs close to O(n) on nearly-sorted data because few elements need to be moved.
Question 6: What governor limit concern arises when using recursive Apex methods to traverse deep data hierarchies in Salesforce?
- CPU time limit
- Stack depth limit (Correct answer)
- Heap size limit
- SOQL query limit
Correct answer: Stack depth limit
Salesforce enforces a maximum stack depth, and deep recursion can cause a stack overflow runtime exception.
Question 7: When implementing a FIFO queue pattern in Apex without a native Queue class, which List methods are used to enqueue and dequeue?
- add() and remove(0) (Correct answer)
- add(0,x) and remove(size-1)
- push() and pop()
- insert() and delete()
Correct answer: add() and remove(0)
add() appends to the end (enqueue) and remove(0) removes the first element (dequeue), implementing FIFO behavior.
Which Salesforce collection type maintains insertion order and allows duplicate values?