leetcode

Leetcode submissions
git clone git://git.laack.co/leetcode.git
Log | Files | Refs | README

rotate-list.dart (1749B)


      1 //Rotate a list k times to the right and return the rotated linked list.
      2 //To solve this I found the remainder of the k / length of linked list 
      3 //then I iterated through the output of that each time moving all of the values one
      4 //to the right in the list.
      5 //Time: 280ms Beats: 100%
      6 //Memory: 144.3MB Beats: 100%
      7 //This problem did not have enough submissions for dart to give accuarte metrics.
      8 //To optimize my solution I would iterate through the list one time first finding all of the values
      9 //that overflowed to the start then adding on the rest of the values. That solution would be O(n) time as opposed
     10 //to my solution which is O(n*k)
     11 /**
     12  * Definition for singly-linked list.
     13  * class ListNode {
     14  *   int val;
     15  *   ListNode? next;
     16  *   ListNode([this.val = 0, this.next]);
     17  * }
     18  */
     19 class Solution {
     20   ListNode? rotateRight(ListNode? head, int k) {
     21       if(head == null){
     22           return head;
     23       }
     24       List<int> vals = [];
     25       while(head != null){
     26           vals.add(head.val);
     27           head = head.next;
     28       }
     29       k = k % vals.length;
     30 
     31 
     32 
     33       List<int> original =  List.from(vals);
     34       for(int x = 0 ; x < k ; ++x){
     35         for(int i = 1 ; i < vals.length ; ++i){
     36             vals[i] = original[i - 1];
     37         }
     38         vals[0] = original[original.length - 1];
     39         original =  List.from(vals);
     40       }
     41       ListNode? start;
     42       ListNode last = new ListNode();
     43       for(int i = 0 ; i < vals.length ; ++i){
     44           ListNode current = new ListNode();
     45           current.val = vals[i];
     46           if(start == null){
     47               start = current;
     48               last = current;
     49           }
     50           else{
     51               last.next = current;
     52               last = current;
     53           }
     54       }
     55       return start;
     56     }
     57 }