Approach to the solution during interviews

I have a query regarding on what kind of approach needs to be taken during the interviews for problem solving.

My general approach is make as many examples as possible with edge cases and invalid inputs and take a generalised approach based on it. But sometimes I do take some cases into consideration that I explictly state them and have a logic for it. Those cases can be solved through the general approach too, but I write some extra code which could lessen the processing run time.


For eg in this problem:

To find the non decreasing array, generalised solution can be written. But I solved it using some special cases too which would avoid some extra processing. The performance gains might not be too much too.

class Solution {
    public boolean checkPossibility(int[] nums) {
        if(nums.length == 0 || nums.length == 1){
			return true;
		}
		else if(sortedArray(nums)){
			return true;
		}
		else if(nums[0] > nums[1]){
			nums[0] = nums[1];
			return sortedArray(nums);
		}
		else{
			for(int i=0;i<nums.length-1;i++){
				if(nums[i] > nums[i+1]){
					if(nums[i-1] > nums[i+1]){
						nums[i+1] = nums[i];
					}
					else{
						nums[i] = nums[i+1];
					}
					break;
				}
			}
			return sortedArray(nums);
		}
    }
    public static boolean sortedArray(int[] nums){
		for(int i=0;i<nums.length - 1;i++){
			if(nums[i] > nums[i+1]){
				return false;
			}
		}
		return true;
	}
}

During an interview, is this an acceptable approach or interviewers are only interested in general approach which would suit all the cases? Please let me know your thoughts and experiences in the comments.

Thank you!!

Comments (0)