Although the time complexity appears to be quadratic due to the while loop nested within the for loop, closer inspection reveals it to be linear. Because the while loop is reached only when currentNum marks the beginning of a sequence (i.e. currentNum-1 is not present in nums), the while loop can only run for n iterations throughout the entire runtime of the algorithm. This means that despite looking like O(n⋅n) complexity, the nested loops actually run in O(n+n)=O(n) time. All other computations occur in constant time, so the overall runtime is linear.
Space complexity : O(n)O(n).
In order to set up O(1)O(1) containment lookups, we allocate linear space for a hash table to store the O(n)O(n) numbers in nums. Other than that, the space complexity is identical to that of the brute force solution.
publicintcanCompleteCircuit(int[] gas, int[] cost) { List<Integer> starts=newLinkedList<>(); int n=gas.length; int total=0; int min=0; int start=0; //dif[i]=change of gas from gas[i] to gas[i+1] or gas[0] for (inti=0; i < n; i++) { total+=gas[i]-cost[i]; if(total<min){ start=(i+1)%n; min=total; } } int tank=0; int count=0; int i=start; while(count!=n){ tank+=gas[i]; tank-=cost[i]; if(tank<0){ break; } i=(i+1)%n; count++; } if(count==n){ return start; } return -1; }
136. Single Number
You must implement a solution with a linear runtime complexity and use only constant extra space.
Approach 4: Bit Manipulation
Concept
If we take XOR of zero and some bit, it will return that bit
a⊕0=a
If we take XOR of two same bits, it will return 0
a⊕a=0
a⊕b⊕a=(a⊕a)⊕b=0⊕b=b
1 2 3 4 5 6 7
publicintsingleNumber(int[] nums) { int res=0; for (int num : nums) { res^=num; } return res; }
ListNode split(ListNode start, int size) { ListNodemidPrev= start; ListNodeend= start.next; //use fast and slow approach to find middle and end of second linked list for (intindex=1; index < size && (midPrev.next != null || end.next != null); index++) { if (end.next != null) { end = (end.next.next != null) ? end.next.next : end.next; } if (midPrev.next != null) { midPrev = midPrev.next; } } ListNodemid= midPrev.next; midPrev.next = null; nextSubList = end.next; end.next = null; // return the start of second linked list return mid; }
voidmerge(ListNode list1, ListNode list2) { ListNodedummyHead=newListNode(); ListNodenewTail= dummyHead; while (list1 != null && list2 != null) { if (list1.val < list2.val) { newTail.next = list1; list1 = list1.next; newTail = newTail.next; } else { newTail.next = list2; list2 = list2.next; newTail = newTail.next; } } newTail.next = (list1 != null) ? list1 : list2; // traverse till the end of merged list to get the newTail while (newTail.next != null) { newTail = newTail.next; } // link the old tail with the head of merged list tail.next = dummyHead.next; // update the old tail to the new tail of merged list tail = newTail; }