File tree Expand file tree Collapse file tree 1 file changed +42
-2
lines changed Expand file tree Collapse file tree 1 file changed +42
-2
lines changed Original file line number Diff line number Diff line change @@ -21,8 +21,14 @@ function intersectionBad(list1, list2) {
2121
2222 return intersection ;
2323}
24-
25- function intersection ( list1 , list2 ) {
24+ /**
25+ * O(m * n)
26+ *
27+ * @param list1
28+ * @param list2
29+ * @returns {* }
30+ */
31+ function intersection2 ( list1 , list2 ) {
2632 let intersection = null ;
2733
2834 for ( let i1 = list1 . head ; i1 ; i1 = i1 . next ) {
@@ -36,4 +42,38 @@ function intersection(list1, list2) {
3642 return intersection ;
3743}
3844
45+ // O(m + n) : using Hash of reference (not value)
46+
47+ /**
48+ * If there's an intersection both ends are the same.
49+ *
50+ * O(n)
51+ *
52+ * @param list1
53+ * @param list2
54+ */
55+ function intersection ( list1 , list2 ) {
56+ if ( list1 . tail !== list2 . tail ) {
57+ return null ;
58+ }
59+
60+ let i1 = list1 . head ;
61+ let i2 = list2 . head ;
62+
63+ if ( list1 . size ( ) > list2 . size ( ) ) {
64+ for ( let i = 0 ; i < list1 . size ( ) - list2 . size ( ) ; i ++ ) { i1 = i1 . next ; }
65+ }
66+
67+ if ( list2 . size ( ) > list1 . size ( ) ) {
68+ for ( let i = 0 ; i < list2 . size ( ) - list1 . size ( ) ; i ++ ) { i2 = i2 . next ; }
69+ }
70+
71+ while ( i1 && i2 && i1 !== i2 ) {
72+ i1 = i1 . next ;
73+ i2 = i2 . next ;
74+ }
75+
76+ return i1 ;
77+ }
78+
3979module . exports = intersection ;
You can’t perform that action at this time.
0 commit comments