1.Finding a row where every entry is \'a\' in a 2-D array. Create an algorithm t
ID: 3575710 • Letter: 1
Question
1.Finding a row where every entry is 'a' in a 2-D array.
Create an algorithm to solve the problem
Identify the factors that would influence the running time, and which can be known before the algorithm or code is executed. Assign names (such as n) to each factor.
Identify the operations that must be counted. You need not count every statement separately. If a group of statements always executes together, treat the group as a single unit. If a method is called, and you do not know the running time of that method, count it as a single operation.
Count the operations performed by the algorithm or code. Express the count as a function of the factors you identified in Step 2. If the count cannot be expressed as a simple function of those factors, define the bounds that can be placed on the count: the best case (lower bound) and worst case (upper bound).
Determine what the Best Case Inputs are, and the Worst Case Inputs are, and the efficiency of your implementation
Transform your count formula into big-O notation by:
Taking the efficiency with worst case input,
Dropping insignificant terms.
Dropping constant coefficients
Explanation / Answer
sub algorithem
===================
first(bool arr[],low,high)
{
if(high >= low)
{
// get the middle index
mid = low + (high - low)/2
// check if the element at middle index is first 1
if ( ( mid == 0 || arr[mid-1] == 0) && arr[mid] == 1)
return mid
// if the element is 0, recur for right side
else if (arr[mid] == 0)
return first(arr, (mid + 1), high)
else // If element is not first 1, recur for left side
return first(arr, low, (mid -1))
}
return -1
}
Time Complexity: O(mLogn) where m is number of rows and n is number of columns in matrix
The worst case time complexity of the above optimized version is also O(mLogn), the will solution work better on average
Another method works in O(m+n) time complexity in worst case.
Step1: Get the index of first (or leftmost) a in the first row.
Step2: Do following for every row after the first row
…IF the element on left of previous leftmost a is not a (other alphabet except a), ignore this row.
…ELSE Move left until any other alphabet except a is found. Update the leftmost index to this index and max_row_index to be the current row.
The time complexity is O(m+n) because we can possibly go as far left as we came ahead in the first step.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.