Please be brutal and let me know what you think of the code below, if written at an interview. Thanks.
Problem: Given an index k, return the kth row of the Pascal's triangle.
For example, given k = 3, Return [1,3,3,1].
Given an index k, return the kth row of the Pascal's triangle.
For example, given k = 3, return [1,3,3,1].
Time it took:
25 minutes (perfectly working solution)Space Complexity:
O(K)Time Complexity:
O(N2)?
Time it took : 25 minutes(perfectly working solution) Space Complexity : O(K) Time Complexity : O(N^2)?
public ArrayList<Integer> getRow(int rowIndex) {
List<ArrayList<Integer>> allList = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> toAdd = new ArrayList<Integer>();
if(rowIndex==0){
toAdd.add(1);
return toAdd;
}
if(rowIndex>=1){
toAdd = new ArrayList<Integer>();
toAdd.add(1);
toAdd.add(1);
allList.add(toAdd);
if(rowIndex==1){
return toAdd;
}
}
for(int i=1; i<rowIndex; i++){
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.add(1);
for(int j=1; j<allList.get(i-1).size(); j++){
temp.add(allList.get(i-1).get(j-1) + allList.get(i-1).get(j));
}
temp.add(1);
allList.add(temp);
}
return allList.get(rowIndex-1);
}